From c5c6e511405882bcf675a3d02c4c22a84ae0b2f7 Mon Sep 17 00:00:00 2001 From: Andreas Gullberg Larsen Date: Mon, 15 Oct 2018 16:54:37 +0200 Subject: [PATCH] Merge generator scripts for WRC and NetFramework (#520) * Merge generator scripts for WRC and NetFramework Handle WRC special cases in code generator scripts instead of in generated code. This removes all the #if sections and merges the "Common" partial code back into each of the WRC and NetFramework files so it is in one place and easy to read. - Arrange huge quantity code into #regions, easier to navigate - Move code generation into functions, easier to read - Add Types.psm1 with types for intellisense on parsed JSON* - Require PowerShell 5.1 (for classes) * VS and VSCode struggle with intellisense when importing types with 'using module', this is relatively new and will probably improve later. * Remove generated common code for quantities * generate-code.bat: Set workdir to scripts folder Needed for 'using module' in powershell to work, it can't have variables. * Regen * Fix WRC compile errors Fix build warns about xmldoc * Fix for code changes --- .../Quantities/Acceleration.Common.g.cs | 801 --------- .../Quantities/AmountOfSubstance.Common.g.cs | 823 --------- .../Quantities/AmplitudeRatio.Common.g.cs | 602 ------- .../Quantities/Angle.Common.g.cs | 822 --------- .../Quantities/ApparentEnergy.Common.g.cs | 581 ------- .../Quantities/ApparentPower.Common.g.cs | 603 ------- .../GeneratedCode/Quantities/Area.Common.g.cs | 801 --------- .../Quantities/AreaDensity.Common.g.cs | 537 ------ .../AreaMomentOfInertia.Common.g.cs | 647 ------- .../Quantities/BitRate.Common.g.cs | 1086 ------------ .../BrakeSpecificFuelConsumption.Common.g.cs | 581 ------- .../Quantities/Capacitance.Common.g.cs | 537 ------ .../Quantities/Density.Common.g.cs | 1351 --------------- .../Quantities/Duration.Common.g.cs | 735 -------- .../Quantities/DynamicViscosity.Common.g.cs | 647 ------- .../Quantities/ElectricAdmittance.Common.g.cs | 603 ------- .../Quantities/ElectricCharge.Common.g.cs | 537 ------ .../ElectricChargeDensity.Common.g.cs | 537 ------ .../ElectricConductance.Common.g.cs | 581 ------- .../ElectricConductivity.Common.g.cs | 537 ------ .../Quantities/ElectricCurrent.Common.g.cs | 691 -------- .../ElectricCurrentDensity.Common.g.cs | 537 ------ .../ElectricCurrentGradient.Common.g.cs | 537 ------ .../Quantities/ElectricField.Common.g.cs | 537 ------ .../Quantities/ElectricInductance.Common.g.cs | 537 ------ .../Quantities/ElectricPotential.Common.g.cs | 625 ------- .../ElectricPotentialAc.Common.g.cs | 624 ------- .../ElectricPotentialDc.Common.g.cs | 624 ------- .../Quantities/ElectricResistance.Common.g.cs | 603 ------- .../ElectricResistivity.Common.g.cs | 603 ------- .../Quantities/Energy.Common.g.cs | 999 ----------- .../Quantities/Entropy.Common.g.cs | 669 -------- .../Quantities/Force.Common.g.cs | 735 -------- .../Quantities/ForceChangeRate.Common.g.cs | 757 --------- .../Quantities/ForcePerLength.Common.g.cs | 713 -------- .../Quantities/Frequency.Common.g.cs | 691 -------- .../Quantities/HeatFlux.Common.g.cs | 867 ---------- .../HeatTransferCoefficient.Common.g.cs | 559 ------- .../Quantities/Illuminance.Common.g.cs | 603 ------- .../Quantities/Information.Common.g.cs | 1086 ------------ .../Quantities/Irradiance.Common.g.cs | 559 ------- .../Quantities/Irradiation.Common.g.cs | 581 ------- .../Quantities/KinematicViscosity.Common.g.cs | 691 -------- .../Quantities/LapseRate.Common.g.cs | 537 ------ .../Quantities/Length.Common.g.cs | 999 ----------- .../Quantities/Level.Common.g.cs | 558 ------- .../Quantities/LinearDensity.Common.g.cs | 581 ------- .../Quantities/LuminousFlux.Common.g.cs | 537 ------ .../Quantities/LuminousIntensity.Common.g.cs | 537 ------ .../Quantities/MagneticField.Common.g.cs | 537 ------ .../Quantities/MagneticFlux.Common.g.cs | 537 ------ .../Quantities/Magnetization.Common.g.cs | 537 ------ .../GeneratedCode/Quantities/Mass.Common.g.cs | 999 ----------- .../Quantities/MassFlow.Common.g.cs | 845 ---------- .../Quantities/MassFlux.Common.g.cs | 559 ------- .../MassMomentOfInertia.Common.g.cs | 1131 ------------- .../Quantities/MolarEnergy.Common.g.cs | 581 ------- .../Quantities/MolarEntropy.Common.g.cs | 581 ------- .../Quantities/MolarMass.Common.g.cs | 779 --------- .../Quantities/Molarity.Common.g.cs | 691 -------- .../Quantities/Permeability.Common.g.cs | 537 ------ .../Quantities/Permittivity.Common.g.cs | 537 ------ .../Quantities/Power.Common.g.cs | 955 ----------- .../Quantities/PowerDensity.Common.g.cs | 1483 ----------------- .../Quantities/PowerRatio.Common.g.cs | 558 ------- .../Quantities/Pressure.Common.g.cs | 1329 --------------- .../Quantities/PressureChangeRate.Common.g.cs | 603 ------- .../Quantities/Ratio.Common.g.cs | 646 ------- .../Quantities/ReactiveEnergy.Common.g.cs | 581 ------- .../Quantities/ReactivePower.Common.g.cs | 603 ------- .../RotationalAcceleration.Common.g.cs | 581 ------- .../Quantities/RotationalSpeed.Common.g.cs | 801 --------- .../RotationalStiffness.Common.g.cs | 581 ------- .../RotationalStiffnessPerLength.Common.g.cs | 581 ------- .../Quantities/SolidAngle.Common.g.cs | 536 ------ .../Quantities/SpecificEnergy.Common.g.cs | 691 -------- .../Quantities/SpecificEntropy.Common.g.cs | 691 -------- .../Quantities/SpecificVolume.Common.g.cs | 559 ------- .../Quantities/SpecificWeight.Common.g.cs | 889 ---------- .../Quantities/Speed.Common.g.cs | 1219 -------------- .../Quantities/Temperature.Common.g.cs | 691 -------- .../TemperatureChangeRate.Common.g.cs | 735 -------- .../Quantities/TemperatureDelta.Common.g.cs | 690 -------- .../ThermalConductivity.Common.g.cs | 559 ------- .../Quantities/ThermalResistance.Common.g.cs | 625 ------- .../Quantities/Torque.Common.g.cs | 977 ----------- .../Quantities/VitaminA.Common.g.cs | 536 ------ .../Quantities/Volume.Common.g.cs | 1439 ---------------- .../Quantities/VolumeFlow.Common.g.cs | 1087 ------------ .../Information.WindowsRuntimeComponent.g.cs | 953 ++++++++++- .../Length.WindowsRuntimeComponent.g.cs | 885 +++++++++- .../Level.WindowsRuntimeComponent.g.cs | 545 +++++- .../UnitsNet.WindowsRuntimeComponent.csproj | 90 +- .../Quantities/Acceleration.extra.cs | 4 + .../Quantities/Information.NetFramework.g.cs | 998 ++++++++++- .../Quantities/Length.NetFramework.g.cs | 888 +++++++++- .../Quantities/Level.NetFramework.g.cs | 588 ++++++- UnitsNet/Scripts/GenerateUnits.ps1 | 108 +- .../Include-GenerateLogarithmicCode.ps1 | 72 - ...clude-GenerateQuantitySourceCodeCommon.ps1 | 603 ------- ...GenerateQuantitySourceCodeNetFramework.ps1 | 992 +++++++++-- ...ntitySourceCodeWindowsRuntimeComponent.ps1 | 245 --- .../Scripts/Include-GenerateTemplates.ps1 | 8 +- ...de-GenerateUnitTestBaseClassSourceCode.ps1 | 18 +- UnitsNet/Scripts/Types.psm1 | 43 + generate-code.bat | 4 +- 106 files changed, 5674 insertions(+), 64573 deletions(-) delete mode 100644 Common/GeneratedCode/Quantities/Acceleration.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Angle.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Area.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/BitRate.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Capacitance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Density.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Duration.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricField.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Energy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Entropy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Force.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Frequency.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Illuminance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Information.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Irradiance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Irradiation.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/LapseRate.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Length.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Level.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MagneticField.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Magnetization.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Mass.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MassFlow.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MassFlux.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/MolarMass.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Molarity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Permeability.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Permittivity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Power.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Pressure.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Ratio.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Speed.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Temperature.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Torque.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/VitaminA.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/Volume.Common.g.cs delete mode 100644 Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs delete mode 100644 UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 delete mode 100644 UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 delete mode 100644 UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 create mode 100644 UnitsNet/Scripts/Types.psm1 diff --git a/Common/GeneratedCode/Quantities/Acceleration.Common.g.cs b/Common/GeneratedCode/Quantities/Acceleration.Common.g.cs deleted file mode 100644 index 6d0a2a93e2..0000000000 --- a/Common/GeneratedCode/Quantities/Acceleration.Common.g.cs +++ /dev/null @@ -1,801 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Acceleration : IQuantity -#else - public partial struct Acceleration : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AccelerationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Acceleration() - { - BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Acceleration(double numericValue, AccelerationUnit unit) - { - if(unit == AccelerationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Acceleration; - - /// - /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. - /// - public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Acceleration quantity. - /// - public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); - - /// - /// Get Acceleration in CentimetersPerSecondSquared. - /// - public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); - - /// - /// Get Acceleration in DecimetersPerSecondSquared. - /// - public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); - - /// - /// Get Acceleration in FeetPerSecondSquared. - /// - public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); - - /// - /// Get Acceleration in InchesPerSecondSquared. - /// - public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); - - /// - /// Get Acceleration in KilometersPerSecondSquared. - /// - public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); - - /// - /// Get Acceleration in KnotsPerHour. - /// - public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); - - /// - /// Get Acceleration in KnotsPerMinute. - /// - public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); - - /// - /// Get Acceleration in KnotsPerSecond. - /// - public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); - - /// - /// Get Acceleration in MetersPerSecondSquared. - /// - public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); - - /// - /// Get Acceleration in MicrometersPerSecondSquared. - /// - public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); - - /// - /// Get Acceleration in MillimetersPerSecondSquared. - /// - public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); - - /// - /// Get Acceleration in NanometersPerSecondSquared. - /// - public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); - - /// - /// Get Acceleration in StandardGravity. - /// - public double StandardGravity => As(AccelerationUnit.StandardGravity); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. - /// - public static Acceleration Zero => new Acceleration(0, BaseUnit); - - /// - /// Get Acceleration from CentimetersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromCentimetersPerSecondSquared(double centimeterspersecondsquared) -#else - public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centimeterspersecondsquared) -#endif - { - double value = (double) centimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); - } - - /// - /// Get Acceleration from DecimetersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromDecimetersPerSecondSquared(double decimeterspersecondsquared) -#else - public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimeterspersecondsquared) -#endif - { - double value = (double) decimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); - } - - /// - /// Get Acceleration from FeetPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromFeetPerSecondSquared(double feetpersecondsquared) -#else - public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) -#endif - { - double value = (double) feetpersecondsquared; - return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); - } - - /// - /// Get Acceleration from InchesPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromInchesPerSecondSquared(double inchespersecondsquared) -#else - public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) -#endif - { - double value = (double) inchespersecondsquared; - return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); - } - - /// - /// Get Acceleration from KilometersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKilometersPerSecondSquared(double kilometerspersecondsquared) -#else - public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilometerspersecondsquared) -#endif - { - double value = (double) kilometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); - } - - /// - /// Get Acceleration from KnotsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerHour(double knotsperhour) -#else - public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) -#endif - { - double value = (double) knotsperhour; - return new Acceleration(value, AccelerationUnit.KnotPerHour); - } - - /// - /// Get Acceleration from KnotsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerMinute(double knotsperminute) -#else - public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) -#endif - { - double value = (double) knotsperminute; - return new Acceleration(value, AccelerationUnit.KnotPerMinute); - } - - /// - /// Get Acceleration from KnotsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerSecond(double knotspersecond) -#else - public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) -#endif - { - double value = (double) knotspersecond; - return new Acceleration(value, AccelerationUnit.KnotPerSecond); - } - - /// - /// Get Acceleration from MetersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMetersPerSecondSquared(double meterspersecondsquared) -#else - public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersecondsquared) -#endif - { - double value = (double) meterspersecondsquared; - return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); - } - - /// - /// Get Acceleration from MicrometersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMicrometersPerSecondSquared(double micrometerspersecondsquared) -#else - public static Acceleration FromMicrometersPerSecondSquared(QuantityValue micrometerspersecondsquared) -#endif - { - double value = (double) micrometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); - } - - /// - /// Get Acceleration from MillimetersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMillimetersPerSecondSquared(double millimeterspersecondsquared) -#else - public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millimeterspersecondsquared) -#endif - { - double value = (double) millimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); - } - - /// - /// Get Acceleration from NanometersPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromNanometersPerSecondSquared(double nanometerspersecondsquared) -#else - public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanometerspersecondsquared) -#endif - { - double value = (double) nanometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); - } - - /// - /// Get Acceleration from StandardGravity. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromStandardGravity(double standardgravity) -#else - public static Acceleration FromStandardGravity(QuantityValue standardgravity) -#endif - { - double value = (double) standardgravity; - return new Acceleration(value, AccelerationUnit.StandardGravity); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Acceleration unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Acceleration From(double value, AccelerationUnit fromUnit) -#else - public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) -#endif - { - return new Acceleration((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AccelerationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Acceleration)) throw new ArgumentException("Expected type Acceleration.", nameof(obj)); - - return CompareTo((Acceleration)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Acceleration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Acceleration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Acceleration other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Acceleration. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AccelerationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Acceleration to another Acceleration with the unit representation . - /// - /// A Acceleration with the specified unit. - public Acceleration ToUnit(AccelerationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Acceleration(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 AsBaseUnit() - { - switch(Unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return _value*0.304800; - case AccelerationUnit.InchPerSecondSquared: return _value*0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; - case AccelerationUnit.KnotPerHour: return _value*0.5144444444444/3600; - case AccelerationUnit.KnotPerMinute: return _value*0.5144444444444/60; - case AccelerationUnit.KnotPerSecond: return _value*0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return _value; - case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; - case AccelerationUnit.StandardGravity: return _value*9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AccelerationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return baseUnitValue/0.304800; - case AccelerationUnit.InchPerSecondSquared: return baseUnitValue/0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; - case AccelerationUnit.KnotPerHour: return baseUnitValue/0.5144444444444*3600; - case AccelerationUnit.KnotPerMinute: return baseUnitValue/0.5144444444444*60; - case AccelerationUnit.KnotPerSecond: return baseUnitValue/0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; - case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; - case AccelerationUnit.StandardGravity: return baseUnitValue/9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Acceleration Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Acceleration result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AccelerationUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AccelerationUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Acceleration ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Acceleration result) - { - result = default(Acceleration); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AccelerationUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AccelerationUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AccelerationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AccelerationUnit unit) - { - unit = AccelerationUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AccelerationUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AccelerationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Acceleration - /// - public static Acceleration MaxValue => new Acceleration(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Acceleration - /// - public static Acceleration MinValue => new Acceleration(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Acceleration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Acceleration.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs b/Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs deleted file mode 100644 index 9c4fb9a21c..0000000000 --- a/Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs +++ /dev/null @@ -1,823 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AmountOfSubstance : IQuantity -#else - public partial struct AmountOfSubstance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AmountOfSubstanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AmountOfSubstance() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - AmountOfSubstance(double numericValue, AmountOfSubstanceUnit unit) - { - if(unit == AmountOfSubstanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AmountOfSubstance; - - /// - /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. - /// - public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AmountOfSubstance quantity. - /// - public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); - - /// - /// Get AmountOfSubstance in Centimoles. - /// - public double Centimoles => As(AmountOfSubstanceUnit.Centimole); - - /// - /// Get AmountOfSubstance in CentipoundMoles. - /// - public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); - - /// - /// Get AmountOfSubstance in Decimoles. - /// - public double Decimoles => As(AmountOfSubstanceUnit.Decimole); - - /// - /// Get AmountOfSubstance in DecipoundMoles. - /// - public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); - - /// - /// Get AmountOfSubstance in Kilomoles. - /// - public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); - - /// - /// Get AmountOfSubstance in KilopoundMoles. - /// - public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); - - /// - /// Get AmountOfSubstance in Micromoles. - /// - public double Micromoles => As(AmountOfSubstanceUnit.Micromole); - - /// - /// Get AmountOfSubstance in MicropoundMoles. - /// - public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); - - /// - /// Get AmountOfSubstance in Millimoles. - /// - public double Millimoles => As(AmountOfSubstanceUnit.Millimole); - - /// - /// Get AmountOfSubstance in MillipoundMoles. - /// - public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); - - /// - /// Get AmountOfSubstance in Moles. - /// - public double Moles => As(AmountOfSubstanceUnit.Mole); - - /// - /// Get AmountOfSubstance in Nanomoles. - /// - public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); - - /// - /// Get AmountOfSubstance in NanopoundMoles. - /// - public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); - - /// - /// Get AmountOfSubstance in PoundMoles. - /// - public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Mole. - /// - public static AmountOfSubstance Zero => new AmountOfSubstance(0, BaseUnit); - - /// - /// Get AmountOfSubstance from Centimoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromCentimoles(double centimoles) -#else - public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) -#endif - { - double value = (double) centimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); - } - - /// - /// Get AmountOfSubstance from CentipoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromCentipoundMoles(double centipoundmoles) -#else - public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) -#endif - { - double value = (double) centipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); - } - - /// - /// Get AmountOfSubstance from Decimoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromDecimoles(double decimoles) -#else - public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) -#endif - { - double value = (double) decimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); - } - - /// - /// Get AmountOfSubstance from DecipoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromDecipoundMoles(double decipoundmoles) -#else - public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) -#endif - { - double value = (double) decipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); - } - - /// - /// Get AmountOfSubstance from Kilomoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromKilomoles(double kilomoles) -#else - public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) -#endif - { - double value = (double) kilomoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); - } - - /// - /// Get AmountOfSubstance from KilopoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromKilopoundMoles(double kilopoundmoles) -#else - public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) -#endif - { - double value = (double) kilopoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); - } - - /// - /// Get AmountOfSubstance from Micromoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMicromoles(double micromoles) -#else - public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) -#endif - { - double value = (double) micromoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); - } - - /// - /// Get AmountOfSubstance from MicropoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMicropoundMoles(double micropoundmoles) -#else - public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) -#endif - { - double value = (double) micropoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); - } - - /// - /// Get AmountOfSubstance from Millimoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMillimoles(double millimoles) -#else - public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) -#endif - { - double value = (double) millimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); - } - - /// - /// Get AmountOfSubstance from MillipoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMillipoundMoles(double millipoundmoles) -#else - public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) -#endif - { - double value = (double) millipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); - } - - /// - /// Get AmountOfSubstance from Moles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMoles(double moles) -#else - public static AmountOfSubstance FromMoles(QuantityValue moles) -#endif - { - double value = (double) moles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); - } - - /// - /// Get AmountOfSubstance from Nanomoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromNanomoles(double nanomoles) -#else - public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) -#endif - { - double value = (double) nanomoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); - } - - /// - /// Get AmountOfSubstance from NanopoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromNanopoundMoles(double nanopoundmoles) -#else - public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) -#endif - { - double value = (double) nanopoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); - } - - /// - /// Get AmountOfSubstance from PoundMoles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromPoundMoles(double poundmoles) -#else - public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) -#endif - { - double value = (double) poundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AmountOfSubstance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUnit) -#else - public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) -#endif - { - return new AmountOfSubstance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AmountOfSubstanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AmountOfSubstance)) throw new ArgumentException("Expected type AmountOfSubstance.", nameof(obj)); - - return CompareTo((AmountOfSubstance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AmountOfSubstance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AmountOfSubstance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmountOfSubstance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmountOfSubstanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . - /// - /// A AmountOfSubstance with the specified unit. - public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AmountOfSubstance(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 AsBaseUnit() - { - switch(Unit) - { - case AmountOfSubstanceUnit.Centimole: return (_value) * 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (_value*453.59237) * 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (_value) * 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (_value*453.59237) * 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (_value) * 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (_value*453.59237) * 1e3d; - case AmountOfSubstanceUnit.Micromole: return (_value) * 1e-6d; - case AmountOfSubstanceUnit.MicropoundMole: return (_value*453.59237) * 1e-6d; - case AmountOfSubstanceUnit.Millimole: return (_value) * 1e-3d; - case AmountOfSubstanceUnit.MillipoundMole: return (_value*453.59237) * 1e-3d; - case AmountOfSubstanceUnit.Mole: return _value; - case AmountOfSubstanceUnit.Nanomole: return (_value) * 1e-9d; - case AmountOfSubstanceUnit.NanopoundMole: return (_value*453.59237) * 1e-9d; - case AmountOfSubstanceUnit.PoundMole: return _value*453.59237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AmountOfSubstanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AmountOfSubstanceUnit.Centimole: return (baseUnitValue) / 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (baseUnitValue/453.59237) / 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (baseUnitValue) / 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (baseUnitValue/453.59237) / 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (baseUnitValue) / 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (baseUnitValue/453.59237) / 1e3d; - case AmountOfSubstanceUnit.Micromole: return (baseUnitValue) / 1e-6d; - case AmountOfSubstanceUnit.MicropoundMole: return (baseUnitValue/453.59237) / 1e-6d; - case AmountOfSubstanceUnit.Millimole: return (baseUnitValue) / 1e-3d; - case AmountOfSubstanceUnit.MillipoundMole: return (baseUnitValue/453.59237) / 1e-3d; - case AmountOfSubstanceUnit.Mole: return baseUnitValue; - case AmountOfSubstanceUnit.Nanomole: return (baseUnitValue) / 1e-9d; - case AmountOfSubstanceUnit.NanopoundMole: return (baseUnitValue/453.59237) / 1e-9d; - case AmountOfSubstanceUnit.PoundMole: return baseUnitValue/453.59237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 AmountOfSubstance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmountOfSubstanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static AmountOfSubstance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AmountOfSubstance result) - { - result = default(AmountOfSubstance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AmountOfSubstanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AmountOfSubstanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmountOfSubstanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AmountOfSubstanceUnit unit) - { - unit = AmountOfSubstanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AmountOfSubstanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AmountOfSubstanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AmountOfSubstance - /// - public static AmountOfSubstance MaxValue => new AmountOfSubstance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AmountOfSubstance - /// - public static AmountOfSubstance MinValue => new AmountOfSubstance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AmountOfSubstance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs b/Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs deleted file mode 100644 index c1fe46ff67..0000000000 --- a/Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs +++ /dev/null @@ -1,602 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AmplitudeRatio : IQuantity -#else - public partial struct AmplitudeRatio : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AmplitudeRatioUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AmplitudeRatio() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - AmplitudeRatio(double numericValue, AmplitudeRatioUnit unit) - { - if(unit == AmplitudeRatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AmplitudeRatio; - - /// - /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. - /// - public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AmplitudeRatio quantity. - /// - public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); - - /// - /// Get AmplitudeRatio in DecibelMicrovolts. - /// - public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); - - /// - /// Get AmplitudeRatio in DecibelMillivolts. - /// - public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); - - /// - /// Get AmplitudeRatio in DecibelsUnloaded. - /// - public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); - - /// - /// Get AmplitudeRatio in DecibelVolts. - /// - public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. - /// - public static AmplitudeRatio Zero => new AmplitudeRatio(0, BaseUnit); - - /// - /// Get AmplitudeRatio from DecibelMicrovolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelMicrovolts(double decibelmicrovolts) -#else - public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) -#endif - { - double value = (double) decibelmicrovolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); - } - - /// - /// Get AmplitudeRatio from DecibelMillivolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelMillivolts(double decibelmillivolts) -#else - public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) -#endif - { - double value = (double) decibelmillivolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); - } - - /// - /// Get AmplitudeRatio from DecibelsUnloaded. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelsUnloaded(double decibelsunloaded) -#else - public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) -#endif - { - double value = (double) decibelsunloaded; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); - } - - /// - /// Get AmplitudeRatio from DecibelVolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelVolts(double decibelvolts) -#else - public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) -#endif - { - double value = (double) decibelvolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AmplitudeRatio unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) -#else - public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) -#endif - { - return new AmplitudeRatio((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AmplitudeRatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AmplitudeRatio)) throw new ArgumentException("Expected type AmplitudeRatio.", nameof(obj)); - - return CompareTo((AmplitudeRatio)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AmplitudeRatio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AmplitudeRatio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmplitudeRatio. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmplitudeRatioUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . - /// - /// A AmplitudeRatio with the specified unit. - public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AmplitudeRatio(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 AsBaseUnit() - { - switch(Unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return _value - 120; - case AmplitudeRatioUnit.DecibelMillivolt: return _value - 60; - case AmplitudeRatioUnit.DecibelUnloaded: return _value - 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AmplitudeRatioUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return baseUnitValue + 120; - case AmplitudeRatioUnit.DecibelMillivolt: return baseUnitValue + 60; - case AmplitudeRatioUnit.DecibelUnloaded: return baseUnitValue + 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 AmplitudeRatio Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmplitudeRatioUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static AmplitudeRatio ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AmplitudeRatio result) - { - result = default(AmplitudeRatio); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AmplitudeRatioUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AmplitudeRatioUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmplitudeRatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AmplitudeRatioUnit unit) - { - unit = AmplitudeRatioUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AmplitudeRatioUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AmplitudeRatioUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AmplitudeRatio - /// - public static AmplitudeRatio MaxValue => new AmplitudeRatio(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AmplitudeRatio - /// - public static AmplitudeRatio MinValue => new AmplitudeRatio(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AmplitudeRatio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Angle.Common.g.cs b/Common/GeneratedCode/Quantities/Angle.Common.g.cs deleted file mode 100644 index 83cdf163dd..0000000000 --- a/Common/GeneratedCode/Quantities/Angle.Common.g.cs +++ /dev/null @@ -1,822 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Angle : IQuantity -#else - public partial struct Angle : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AngleUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Angle() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Angle(double numericValue, AngleUnit unit) - { - if(unit == AngleUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Angle; - - /// - /// The base unit of Angle, which is Degree. All conversions go via this value. - /// - public static AngleUnit BaseUnit => AngleUnit.Degree; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Angle quantity. - /// - public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); - - /// - /// Get Angle in Arcminutes. - /// - public double Arcminutes => As(AngleUnit.Arcminute); - - /// - /// Get Angle in Arcseconds. - /// - public double Arcseconds => As(AngleUnit.Arcsecond); - - /// - /// Get Angle in Centiradians. - /// - public double Centiradians => As(AngleUnit.Centiradian); - - /// - /// Get Angle in Deciradians. - /// - public double Deciradians => As(AngleUnit.Deciradian); - - /// - /// Get Angle in Degrees. - /// - public double Degrees => As(AngleUnit.Degree); - - /// - /// Get Angle in Gradians. - /// - public double Gradians => As(AngleUnit.Gradian); - - /// - /// Get Angle in Microdegrees. - /// - public double Microdegrees => As(AngleUnit.Microdegree); - - /// - /// Get Angle in Microradians. - /// - public double Microradians => As(AngleUnit.Microradian); - - /// - /// Get Angle in Millidegrees. - /// - public double Millidegrees => As(AngleUnit.Millidegree); - - /// - /// Get Angle in Milliradians. - /// - public double Milliradians => As(AngleUnit.Milliradian); - - /// - /// Get Angle in Nanodegrees. - /// - public double Nanodegrees => As(AngleUnit.Nanodegree); - - /// - /// Get Angle in Nanoradians. - /// - public double Nanoradians => As(AngleUnit.Nanoradian); - - /// - /// Get Angle in Radians. - /// - public double Radians => As(AngleUnit.Radian); - - /// - /// Get Angle in Revolutions. - /// - public double Revolutions => As(AngleUnit.Revolution); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Degree. - /// - public static Angle Zero => new Angle(0, BaseUnit); - - /// - /// Get Angle from Arcminutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromArcminutes(double arcminutes) -#else - public static Angle FromArcminutes(QuantityValue arcminutes) -#endif - { - double value = (double) arcminutes; - return new Angle(value, AngleUnit.Arcminute); - } - - /// - /// Get Angle from Arcseconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromArcseconds(double arcseconds) -#else - public static Angle FromArcseconds(QuantityValue arcseconds) -#endif - { - double value = (double) arcseconds; - return new Angle(value, AngleUnit.Arcsecond); - } - - /// - /// Get Angle from Centiradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromCentiradians(double centiradians) -#else - public static Angle FromCentiradians(QuantityValue centiradians) -#endif - { - double value = (double) centiradians; - return new Angle(value, AngleUnit.Centiradian); - } - - /// - /// Get Angle from Deciradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromDeciradians(double deciradians) -#else - public static Angle FromDeciradians(QuantityValue deciradians) -#endif - { - double value = (double) deciradians; - return new Angle(value, AngleUnit.Deciradian); - } - - /// - /// Get Angle from Degrees. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromDegrees(double degrees) -#else - public static Angle FromDegrees(QuantityValue degrees) -#endif - { - double value = (double) degrees; - return new Angle(value, AngleUnit.Degree); - } - - /// - /// Get Angle from Gradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromGradians(double gradians) -#else - public static Angle FromGradians(QuantityValue gradians) -#endif - { - double value = (double) gradians; - return new Angle(value, AngleUnit.Gradian); - } - - /// - /// Get Angle from Microdegrees. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMicrodegrees(double microdegrees) -#else - public static Angle FromMicrodegrees(QuantityValue microdegrees) -#endif - { - double value = (double) microdegrees; - return new Angle(value, AngleUnit.Microdegree); - } - - /// - /// Get Angle from Microradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMicroradians(double microradians) -#else - public static Angle FromMicroradians(QuantityValue microradians) -#endif - { - double value = (double) microradians; - return new Angle(value, AngleUnit.Microradian); - } - - /// - /// Get Angle from Millidegrees. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMillidegrees(double millidegrees) -#else - public static Angle FromMillidegrees(QuantityValue millidegrees) -#endif - { - double value = (double) millidegrees; - return new Angle(value, AngleUnit.Millidegree); - } - - /// - /// Get Angle from Milliradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMilliradians(double milliradians) -#else - public static Angle FromMilliradians(QuantityValue milliradians) -#endif - { - double value = (double) milliradians; - return new Angle(value, AngleUnit.Milliradian); - } - - /// - /// Get Angle from Nanodegrees. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNanodegrees(double nanodegrees) -#else - public static Angle FromNanodegrees(QuantityValue nanodegrees) -#endif - { - double value = (double) nanodegrees; - return new Angle(value, AngleUnit.Nanodegree); - } - - /// - /// Get Angle from Nanoradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNanoradians(double nanoradians) -#else - public static Angle FromNanoradians(QuantityValue nanoradians) -#endif - { - double value = (double) nanoradians; - return new Angle(value, AngleUnit.Nanoradian); - } - - /// - /// Get Angle from Radians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromRadians(double radians) -#else - public static Angle FromRadians(QuantityValue radians) -#endif - { - double value = (double) radians; - return new Angle(value, AngleUnit.Radian); - } - - /// - /// Get Angle from Revolutions. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromRevolutions(double revolutions) -#else - public static Angle FromRevolutions(QuantityValue revolutions) -#endif - { - double value = (double) revolutions; - return new Angle(value, AngleUnit.Revolution); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Angle unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Angle From(double value, AngleUnit fromUnit) -#else - public static Angle From(QuantityValue value, AngleUnit fromUnit) -#endif - { - return new Angle((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AngleUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Angle)) throw new ArgumentException("Expected type Angle.", nameof(obj)); - - return CompareTo((Angle)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Angle other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Angle within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Angle. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AngleUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Angle to another Angle with the unit representation . - /// - /// A Angle with the specified unit. - public Angle ToUnit(AngleUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Angle(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 AsBaseUnit() - { - switch(Unit) - { - case AngleUnit.Arcminute: return _value/60; - case AngleUnit.Arcsecond: return _value/3600; - case AngleUnit.Centiradian: return (_value*180/Math.PI) * 1e-2d; - case AngleUnit.Deciradian: return (_value*180/Math.PI) * 1e-1d; - case AngleUnit.Degree: return _value; - case AngleUnit.Gradian: return _value*0.9; - case AngleUnit.Microdegree: return (_value) * 1e-6d; - case AngleUnit.Microradian: return (_value*180/Math.PI) * 1e-6d; - case AngleUnit.Millidegree: return (_value) * 1e-3d; - case AngleUnit.Milliradian: return (_value*180/Math.PI) * 1e-3d; - case AngleUnit.Nanodegree: return (_value) * 1e-9d; - case AngleUnit.Nanoradian: return (_value*180/Math.PI) * 1e-9d; - case AngleUnit.Radian: return _value*180/Math.PI; - case AngleUnit.Revolution: return _value*360; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AngleUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AngleUnit.Arcminute: return baseUnitValue*60; - case AngleUnit.Arcsecond: return baseUnitValue*3600; - case AngleUnit.Centiradian: return (baseUnitValue/180*Math.PI) / 1e-2d; - case AngleUnit.Deciradian: return (baseUnitValue/180*Math.PI) / 1e-1d; - case AngleUnit.Degree: return baseUnitValue; - case AngleUnit.Gradian: return baseUnitValue/0.9; - case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; - case AngleUnit.Microradian: return (baseUnitValue/180*Math.PI) / 1e-6d; - case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; - case AngleUnit.Milliradian: return (baseUnitValue/180*Math.PI) / 1e-3d; - case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; - case AngleUnit.Nanoradian: return (baseUnitValue/180*Math.PI) / 1e-9d; - case AngleUnit.Radian: return baseUnitValue/180*Math.PI; - case AngleUnit.Revolution: return baseUnitValue/360; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Angle Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Angle result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AngleUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AngleUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Angle ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Angle result) - { - result = default(Angle); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AngleUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AngleUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AngleUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AngleUnit unit) - { - unit = AngleUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AngleUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AngleUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Angle - /// - public static Angle MaxValue => new Angle(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Angle - /// - public static Angle MinValue => new Angle(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Angle.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Angle.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs deleted file mode 100644 index 0ecc9b3128..0000000000 --- a/Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ApparentEnergy : IQuantity -#else - public partial struct ApparentEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ApparentEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ApparentEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ApparentEnergy(double numericValue, ApparentEnergyUnit unit) - { - if(unit == ApparentEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ApparentEnergy; - - /// - /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. - /// - public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ApparentEnergy quantity. - /// - public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); - - /// - /// Get ApparentEnergy in KilovoltampereHours. - /// - public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); - - /// - /// Get ApparentEnergy in MegavoltampereHours. - /// - public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); - - /// - /// Get ApparentEnergy in VoltampereHours. - /// - public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. - /// - public static ApparentEnergy Zero => new ApparentEnergy(0, BaseUnit); - - /// - /// Get ApparentEnergy from KilovoltampereHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromKilovoltampereHours(double kilovoltamperehours) -#else - public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) -#endif - { - double value = (double) kilovoltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); - } - - /// - /// Get ApparentEnergy from MegavoltampereHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromMegavoltampereHours(double megavoltamperehours) -#else - public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) -#endif - { - double value = (double) megavoltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); - } - - /// - /// Get ApparentEnergy from VoltampereHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromVoltampereHours(double voltamperehours) -#else - public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) -#endif - { - double value = (double) voltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ApparentEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) -#else - public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) -#endif - { - return new ApparentEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ApparentEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ApparentEnergy)) throw new ArgumentException("Expected type ApparentEnergy.", nameof(obj)); - - return CompareTo((ApparentEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ApparentEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ApparentEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ApparentEnergy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ApparentEnergy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation . - /// - /// A ApparentEnergy with the specified unit. - public ApparentEnergy ToUnit(ApparentEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ApparentEnergy(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 AsBaseUnit() - { - switch(Unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (_value) * 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (_value) * 1e6d; - case ApparentEnergyUnit.VoltampereHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ApparentEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (baseUnitValue) / 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (baseUnitValue) / 1e6d; - case ApparentEnergyUnit.VoltampereHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ApparentEnergy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentEnergyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ApparentEnergy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ApparentEnergy result) - { - result = default(ApparentEnergy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ApparentEnergyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ApparentEnergyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ApparentEnergyUnit unit) - { - unit = ApparentEnergyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ApparentEnergyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ApparentEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ApparentEnergy - /// - public static ApparentEnergy MaxValue => new ApparentEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ApparentEnergy - /// - public static ApparentEnergy MinValue => new ApparentEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ApparentEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs b/Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs deleted file mode 100644 index 9df3c1f890..0000000000 --- a/Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ApparentPower : IQuantity -#else - public partial struct ApparentPower : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ApparentPowerUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ApparentPower() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ApparentPower(double numericValue, ApparentPowerUnit unit) - { - if(unit == ApparentPowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ApparentPower; - - /// - /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. - /// - public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ApparentPower quantity. - /// - public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); - - /// - /// Get ApparentPower in Gigavoltamperes. - /// - public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); - - /// - /// Get ApparentPower in Kilovoltamperes. - /// - public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); - - /// - /// Get ApparentPower in Megavoltamperes. - /// - public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); - - /// - /// Get ApparentPower in Voltamperes. - /// - public double Voltamperes => As(ApparentPowerUnit.Voltampere); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. - /// - public static ApparentPower Zero => new ApparentPower(0, BaseUnit); - - /// - /// Get ApparentPower from Gigavoltamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromGigavoltamperes(double gigavoltamperes) -#else - public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) -#endif - { - double value = (double) gigavoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); - } - - /// - /// Get ApparentPower from Kilovoltamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromKilovoltamperes(double kilovoltamperes) -#else - public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) -#endif - { - double value = (double) kilovoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); - } - - /// - /// Get ApparentPower from Megavoltamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromMegavoltamperes(double megavoltamperes) -#else - public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) -#endif - { - double value = (double) megavoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); - } - - /// - /// Get ApparentPower from Voltamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromVoltamperes(double voltamperes) -#else - public static ApparentPower FromVoltamperes(QuantityValue voltamperes) -#endif - { - double value = (double) voltamperes; - return new ApparentPower(value, ApparentPowerUnit.Voltampere); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ApparentPower unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ApparentPower From(double value, ApparentPowerUnit fromUnit) -#else - public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) -#endif - { - return new ApparentPower((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ApparentPowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ApparentPower)) throw new ArgumentException("Expected type ApparentPower.", nameof(obj)); - - return CompareTo((ApparentPower)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ApparentPower other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ApparentPower within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ApparentPower other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ApparentPower. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentPowerUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ApparentPower to another ApparentPower with the unit representation . - /// - /// A ApparentPower with the specified unit. - public ApparentPower ToUnit(ApparentPowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ApparentPower(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 AsBaseUnit() - { - switch(Unit) - { - case ApparentPowerUnit.Gigavoltampere: return (_value) * 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (_value) * 1e3d; - case ApparentPowerUnit.Megavoltampere: return (_value) * 1e6d; - case ApparentPowerUnit.Voltampere: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ApparentPowerUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ApparentPowerUnit.Gigavoltampere: return (baseUnitValue) / 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (baseUnitValue) / 1e3d; - case ApparentPowerUnit.Megavoltampere: return (baseUnitValue) / 1e6d; - case ApparentPowerUnit.Voltampere: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ApparentPower Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ApparentPower result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentPowerUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ApparentPowerUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ApparentPower ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ApparentPower result) - { - result = default(ApparentPower); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ApparentPowerUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ApparentPowerUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentPowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ApparentPowerUnit unit) - { - unit = ApparentPowerUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ApparentPowerUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ApparentPowerUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ApparentPower - /// - public static ApparentPower MaxValue => new ApparentPower(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ApparentPower - /// - public static ApparentPower MinValue => new ApparentPower(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ApparentPower.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ApparentPower.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Area.Common.g.cs b/Common/GeneratedCode/Quantities/Area.Common.g.cs deleted file mode 100644 index c58c270ae2..0000000000 --- a/Common/GeneratedCode/Quantities/Area.Common.g.cs +++ /dev/null @@ -1,801 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Area : IQuantity -#else - public partial struct Area : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Area() - { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Area(double numericValue, AreaUnit unit) - { - if(unit == AreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Area; - - /// - /// The base unit of Area, which is SquareMeter. All conversions go via this value. - /// - public static AreaUnit BaseUnit => AreaUnit.SquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Area quantity. - /// - public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); - - /// - /// Get Area in Acres. - /// - public double Acres => As(AreaUnit.Acre); - - /// - /// Get Area in Hectares. - /// - public double Hectares => As(AreaUnit.Hectare); - - /// - /// Get Area in SquareCentimeters. - /// - public double SquareCentimeters => As(AreaUnit.SquareCentimeter); - - /// - /// Get Area in SquareDecimeters. - /// - public double SquareDecimeters => As(AreaUnit.SquareDecimeter); - - /// - /// Get Area in SquareFeet. - /// - public double SquareFeet => As(AreaUnit.SquareFoot); - - /// - /// Get Area in SquareInches. - /// - public double SquareInches => As(AreaUnit.SquareInch); - - /// - /// Get Area in SquareKilometers. - /// - public double SquareKilometers => As(AreaUnit.SquareKilometer); - - /// - /// Get Area in SquareMeters. - /// - public double SquareMeters => As(AreaUnit.SquareMeter); - - /// - /// Get Area in SquareMicrometers. - /// - public double SquareMicrometers => As(AreaUnit.SquareMicrometer); - - /// - /// Get Area in SquareMiles. - /// - public double SquareMiles => As(AreaUnit.SquareMile); - - /// - /// Get Area in SquareMillimeters. - /// - public double SquareMillimeters => As(AreaUnit.SquareMillimeter); - - /// - /// Get Area in SquareYards. - /// - public double SquareYards => As(AreaUnit.SquareYard); - - /// - /// Get Area in UsSurveySquareFeet. - /// - public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. - /// - public static Area Zero => new Area(0, BaseUnit); - - /// - /// Get Area from Acres. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromAcres(double acres) -#else - public static Area FromAcres(QuantityValue acres) -#endif - { - double value = (double) acres; - return new Area(value, AreaUnit.Acre); - } - - /// - /// Get Area from Hectares. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromHectares(double hectares) -#else - public static Area FromHectares(QuantityValue hectares) -#endif - { - double value = (double) hectares; - return new Area(value, AreaUnit.Hectare); - } - - /// - /// Get Area from SquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareCentimeters(double squarecentimeters) -#else - public static Area FromSquareCentimeters(QuantityValue squarecentimeters) -#endif - { - double value = (double) squarecentimeters; - return new Area(value, AreaUnit.SquareCentimeter); - } - - /// - /// Get Area from SquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareDecimeters(double squaredecimeters) -#else - public static Area FromSquareDecimeters(QuantityValue squaredecimeters) -#endif - { - double value = (double) squaredecimeters; - return new Area(value, AreaUnit.SquareDecimeter); - } - - /// - /// Get Area from SquareFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareFeet(double squarefeet) -#else - public static Area FromSquareFeet(QuantityValue squarefeet) -#endif - { - double value = (double) squarefeet; - return new Area(value, AreaUnit.SquareFoot); - } - - /// - /// Get Area from SquareInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareInches(double squareinches) -#else - public static Area FromSquareInches(QuantityValue squareinches) -#endif - { - double value = (double) squareinches; - return new Area(value, AreaUnit.SquareInch); - } - - /// - /// Get Area from SquareKilometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareKilometers(double squarekilometers) -#else - public static Area FromSquareKilometers(QuantityValue squarekilometers) -#endif - { - double value = (double) squarekilometers; - return new Area(value, AreaUnit.SquareKilometer); - } - - /// - /// Get Area from SquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMeters(double squaremeters) -#else - public static Area FromSquareMeters(QuantityValue squaremeters) -#endif - { - double value = (double) squaremeters; - return new Area(value, AreaUnit.SquareMeter); - } - - /// - /// Get Area from SquareMicrometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMicrometers(double squaremicrometers) -#else - public static Area FromSquareMicrometers(QuantityValue squaremicrometers) -#endif - { - double value = (double) squaremicrometers; - return new Area(value, AreaUnit.SquareMicrometer); - } - - /// - /// Get Area from SquareMiles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMiles(double squaremiles) -#else - public static Area FromSquareMiles(QuantityValue squaremiles) -#endif - { - double value = (double) squaremiles; - return new Area(value, AreaUnit.SquareMile); - } - - /// - /// Get Area from SquareMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMillimeters(double squaremillimeters) -#else - public static Area FromSquareMillimeters(QuantityValue squaremillimeters) -#endif - { - double value = (double) squaremillimeters; - return new Area(value, AreaUnit.SquareMillimeter); - } - - /// - /// Get Area from SquareYards. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareYards(double squareyards) -#else - public static Area FromSquareYards(QuantityValue squareyards) -#endif - { - double value = (double) squareyards; - return new Area(value, AreaUnit.SquareYard); - } - - /// - /// Get Area from UsSurveySquareFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromUsSurveySquareFeet(double ussurveysquarefeet) -#else - public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) -#endif - { - double value = (double) ussurveysquarefeet; - return new Area(value, AreaUnit.UsSurveySquareFoot); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Area unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Area From(double value, AreaUnit fromUnit) -#else - public static Area From(QuantityValue value, AreaUnit fromUnit) -#endif - { - return new Area((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Area)) throw new ArgumentException("Expected type Area.", nameof(obj)); - - return CompareTo((Area)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Area other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Area within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Area other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Area. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Area to another Area with the unit representation . - /// - /// A Area with the specified unit. - public Area ToUnit(AreaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Area(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 AsBaseUnit() - { - switch(Unit) - { - case AreaUnit.Acre: return _value*4046.85642; - case AreaUnit.Hectare: return _value*1e4; - case AreaUnit.SquareCentimeter: return _value*1e-4; - case AreaUnit.SquareDecimeter: return _value*1e-2; - case AreaUnit.SquareFoot: return _value*0.092903; - case AreaUnit.SquareInch: return _value*0.00064516; - case AreaUnit.SquareKilometer: return _value*1e6; - case AreaUnit.SquareMeter: return _value; - case AreaUnit.SquareMicrometer: return _value*1e-12; - case AreaUnit.SquareMile: return _value*2.59e6; - case AreaUnit.SquareMillimeter: return _value*1e-6; - case AreaUnit.SquareYard: return _value*0.836127; - case AreaUnit.UsSurveySquareFoot: return _value*0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaUnit.Acre: return baseUnitValue/4046.85642; - case AreaUnit.Hectare: return baseUnitValue/1e4; - case AreaUnit.SquareCentimeter: return baseUnitValue/1e-4; - case AreaUnit.SquareDecimeter: return baseUnitValue/1e-2; - case AreaUnit.SquareFoot: return baseUnitValue/0.092903; - case AreaUnit.SquareInch: return baseUnitValue/0.00064516; - case AreaUnit.SquareKilometer: return baseUnitValue/1e6; - case AreaUnit.SquareMeter: return baseUnitValue; - case AreaUnit.SquareMicrometer: return baseUnitValue/1e-12; - case AreaUnit.SquareMile: return baseUnitValue/2.59e6; - case AreaUnit.SquareMillimeter: return baseUnitValue/1e-6; - case AreaUnit.SquareYard: return baseUnitValue/0.836127; - case AreaUnit.UsSurveySquareFoot: return baseUnitValue/0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Area Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Area result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AreaUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Area ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Area result) - { - result = default(Area); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AreaUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AreaUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AreaUnit unit) - { - unit = AreaUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AreaUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AreaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Area - /// - public static Area MaxValue => new Area(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Area - /// - public static Area MinValue => new Area(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Area.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Area.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs b/Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs deleted file mode 100644 index 2499aca212..0000000000 --- a/Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The area density of a two-dimensional object is calculated as the mass per unit area. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AreaDensity : IQuantity -#else - public partial struct AreaDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AreaDensity() - { - BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - AreaDensity(double numericValue, AreaDensityUnit unit) - { - if(unit == AreaDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AreaDensity; - - /// - /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. - /// - public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AreaDensity quantity. - /// - public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); - - /// - /// Get AreaDensity in KilogramsPerSquareMeter. - /// - public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. - /// - public static AreaDensity Zero => new AreaDensity(0, BaseUnit); - - /// - /// Get AreaDensity from KilogramsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaDensity FromKilogramsPerSquareMeter(double kilogramspersquaremeter) -#else - public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) -#endif - { - double value = (double) kilogramspersquaremeter; - return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AreaDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AreaDensity From(double value, AreaDensityUnit fromUnit) -#else - public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) -#endif - { - return new AreaDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AreaDensity)) throw new ArgumentException("Expected type AreaDensity.", nameof(obj)); - - return CompareTo((AreaDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AreaDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AreaDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AreaDensity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaDensity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AreaDensity to another AreaDensity with the unit representation . - /// - /// A AreaDensity with the specified unit. - public AreaDensity ToUnit(AreaDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AreaDensity(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 AsBaseUnit() - { - switch(Unit) - { - case AreaDensityUnit.KilogramPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 AreaDensity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AreaDensity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaDensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AreaDensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static AreaDensity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AreaDensity result) - { - result = default(AreaDensity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AreaDensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AreaDensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AreaDensityUnit unit) - { - unit = AreaDensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AreaDensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AreaDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AreaDensity - /// - public static AreaDensity MaxValue => new AreaDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AreaDensity - /// - public static AreaDensity MinValue => new AreaDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AreaDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AreaDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs b/Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs deleted file mode 100644 index 0b60cdd202..0000000000 --- a/Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs +++ /dev/null @@ -1,647 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A geometric property of an area that reflects how its points are distributed with regard to an axis. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AreaMomentOfInertia : IQuantity -#else - public partial struct AreaMomentOfInertia : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaMomentOfInertiaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AreaMomentOfInertia() - { - BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - AreaMomentOfInertia(double numericValue, AreaMomentOfInertiaUnit unit) - { - if(unit == AreaMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AreaMomentOfInertia; - - /// - /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. - /// - public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AreaMomentOfInertia quantity. - /// - public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); - - /// - /// Get AreaMomentOfInertia in CentimetersToTheFourth. - /// - public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); - - /// - /// Get AreaMomentOfInertia in DecimetersToTheFourth. - /// - public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); - - /// - /// Get AreaMomentOfInertia in FeetToTheFourth. - /// - public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); - - /// - /// Get AreaMomentOfInertia in InchesToTheFourth. - /// - public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); - - /// - /// Get AreaMomentOfInertia in MetersToTheFourth. - /// - public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); - - /// - /// Get AreaMomentOfInertia in MillimetersToTheFourth. - /// - public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. - /// - public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(0, BaseUnit); - - /// - /// Get AreaMomentOfInertia from CentimetersToTheFourth. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromCentimetersToTheFourth(double centimeterstothefourth) -#else - public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) -#endif - { - double value = (double) centimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from DecimetersToTheFourth. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromDecimetersToTheFourth(double decimeterstothefourth) -#else - public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) -#endif - { - double value = (double) decimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from FeetToTheFourth. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromFeetToTheFourth(double feettothefourth) -#else - public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) -#endif - { - double value = (double) feettothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from InchesToTheFourth. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromInchesToTheFourth(double inchestothefourth) -#else - public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) -#endif - { - double value = (double) inchestothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from MetersToTheFourth. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromMetersToTheFourth(double meterstothefourth) -#else - public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) -#endif - { - double value = (double) meterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from MillimetersToTheFourth. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromMillimetersToTheFourth(double millimeterstothefourth) -#else - public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) -#endif - { - double value = (double) millimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AreaMomentOfInertia unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fromUnit) -#else - public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) -#endif - { - return new AreaMomentOfInertia((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AreaMomentOfInertia)) throw new ArgumentException("Expected type AreaMomentOfInertia.", nameof(obj)); - - return CompareTo((AreaMomentOfInertia)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AreaMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AreaMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaMomentOfInertia. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaMomentOfInertiaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . - /// - /// A AreaMomentOfInertia with the specified unit. - public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AreaMomentOfInertia(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 AsBaseUnit() - { - switch(Unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return _value/1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return _value/1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return _value*Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return _value*Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return _value; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return _value/1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaMomentOfInertiaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return baseUnitValue*1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return baseUnitValue*1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return baseUnitValue/Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return baseUnitValue/Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return baseUnitValue; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return baseUnitValue*1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 AreaMomentOfInertia Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static AreaMomentOfInertia ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AreaMomentOfInertia result) - { - result = default(AreaMomentOfInertia); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static AreaMomentOfInertiaUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == AreaMomentOfInertiaUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaMomentOfInertiaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out AreaMomentOfInertiaUnit unit) - { - unit = AreaMomentOfInertiaUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == AreaMomentOfInertiaUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AreaMomentOfInertiaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AreaMomentOfInertia - /// - public static AreaMomentOfInertia MaxValue => new AreaMomentOfInertia(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AreaMomentOfInertia - /// - public static AreaMomentOfInertia MinValue => new AreaMomentOfInertia(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AreaMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/BitRate.Common.g.cs b/Common/GeneratedCode/Quantities/BitRate.Common.g.cs deleted file mode 100644 index 1ad1293a07..0000000000 --- a/Common/GeneratedCode/Quantities/BitRate.Common.g.cs +++ /dev/null @@ -1,1086 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class BitRate : IQuantity -#else - public partial struct BitRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly BitRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static BitRate() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - BitRate(decimal numericValue, BitRateUnit unit) - { - if(unit == BitRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = numericValue; - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.BitRate; - - /// - /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. - /// - public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the BitRate quantity. - /// - public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); - - /// - /// Get BitRate in BitsPerSecond. - /// - public double BitsPerSecond => As(BitRateUnit.BitPerSecond); - - /// - /// Get BitRate in BytesPerSecond. - /// - public double BytesPerSecond => As(BitRateUnit.BytePerSecond); - - /// - /// Get BitRate in ExabitsPerSecond. - /// - public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); - - /// - /// Get BitRate in ExabytesPerSecond. - /// - public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); - - /// - /// Get BitRate in ExbibitsPerSecond. - /// - public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); - - /// - /// Get BitRate in ExbibytesPerSecond. - /// - public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); - - /// - /// Get BitRate in GibibitsPerSecond. - /// - public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); - - /// - /// Get BitRate in GibibytesPerSecond. - /// - public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); - - /// - /// Get BitRate in GigabitsPerSecond. - /// - public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); - - /// - /// Get BitRate in GigabytesPerSecond. - /// - public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); - - /// - /// Get BitRate in KibibitsPerSecond. - /// - public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); - - /// - /// Get BitRate in KibibytesPerSecond. - /// - public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); - - /// - /// Get BitRate in KilobitsPerSecond. - /// - public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); - - /// - /// Get BitRate in KilobytesPerSecond. - /// - public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); - - /// - /// Get BitRate in MebibitsPerSecond. - /// - public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); - - /// - /// Get BitRate in MebibytesPerSecond. - /// - public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); - - /// - /// Get BitRate in MegabitsPerSecond. - /// - public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); - - /// - /// Get BitRate in MegabytesPerSecond. - /// - public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); - - /// - /// Get BitRate in PebibitsPerSecond. - /// - public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); - - /// - /// Get BitRate in PebibytesPerSecond. - /// - public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); - - /// - /// Get BitRate in PetabitsPerSecond. - /// - public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); - - /// - /// Get BitRate in PetabytesPerSecond. - /// - public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); - - /// - /// Get BitRate in TebibitsPerSecond. - /// - public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); - - /// - /// Get BitRate in TebibytesPerSecond. - /// - public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); - - /// - /// Get BitRate in TerabitsPerSecond. - /// - public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); - - /// - /// Get BitRate in TerabytesPerSecond. - /// - public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. - /// - public static BitRate Zero => new BitRate(0, BaseUnit); - - /// - /// Get BitRate from BitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromBitsPerSecond(double bitspersecond) -#else - public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) -#endif - { - decimal value = (decimal) bitspersecond; - return new BitRate(value, BitRateUnit.BitPerSecond); - } - - /// - /// Get BitRate from BytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromBytesPerSecond(double bytespersecond) -#else - public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) -#endif - { - decimal value = (decimal) bytespersecond; - return new BitRate(value, BitRateUnit.BytePerSecond); - } - - /// - /// Get BitRate from ExabitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExabitsPerSecond(double exabitspersecond) -#else - public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) -#endif - { - decimal value = (decimal) exabitspersecond; - return new BitRate(value, BitRateUnit.ExabitPerSecond); - } - - /// - /// Get BitRate from ExabytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExabytesPerSecond(double exabytespersecond) -#else - public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) -#endif - { - decimal value = (decimal) exabytespersecond; - return new BitRate(value, BitRateUnit.ExabytePerSecond); - } - - /// - /// Get BitRate from ExbibitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExbibitsPerSecond(double exbibitspersecond) -#else - public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) -#endif - { - decimal value = (decimal) exbibitspersecond; - return new BitRate(value, BitRateUnit.ExbibitPerSecond); - } - - /// - /// Get BitRate from ExbibytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExbibytesPerSecond(double exbibytespersecond) -#else - public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) -#endif - { - decimal value = (decimal) exbibytespersecond; - return new BitRate(value, BitRateUnit.ExbibytePerSecond); - } - - /// - /// Get BitRate from GibibitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGibibitsPerSecond(double gibibitspersecond) -#else - public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) -#endif - { - decimal value = (decimal) gibibitspersecond; - return new BitRate(value, BitRateUnit.GibibitPerSecond); - } - - /// - /// Get BitRate from GibibytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGibibytesPerSecond(double gibibytespersecond) -#else - public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) -#endif - { - decimal value = (decimal) gibibytespersecond; - return new BitRate(value, BitRateUnit.GibibytePerSecond); - } - - /// - /// Get BitRate from GigabitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGigabitsPerSecond(double gigabitspersecond) -#else - public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) -#endif - { - decimal value = (decimal) gigabitspersecond; - return new BitRate(value, BitRateUnit.GigabitPerSecond); - } - - /// - /// Get BitRate from GigabytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGigabytesPerSecond(double gigabytespersecond) -#else - public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) -#endif - { - decimal value = (decimal) gigabytespersecond; - return new BitRate(value, BitRateUnit.GigabytePerSecond); - } - - /// - /// Get BitRate from KibibitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKibibitsPerSecond(double kibibitspersecond) -#else - public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) -#endif - { - decimal value = (decimal) kibibitspersecond; - return new BitRate(value, BitRateUnit.KibibitPerSecond); - } - - /// - /// Get BitRate from KibibytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKibibytesPerSecond(double kibibytespersecond) -#else - public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) -#endif - { - decimal value = (decimal) kibibytespersecond; - return new BitRate(value, BitRateUnit.KibibytePerSecond); - } - - /// - /// Get BitRate from KilobitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKilobitsPerSecond(double kilobitspersecond) -#else - public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) -#endif - { - decimal value = (decimal) kilobitspersecond; - return new BitRate(value, BitRateUnit.KilobitPerSecond); - } - - /// - /// Get BitRate from KilobytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKilobytesPerSecond(double kilobytespersecond) -#else - public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) -#endif - { - decimal value = (decimal) kilobytespersecond; - return new BitRate(value, BitRateUnit.KilobytePerSecond); - } - - /// - /// Get BitRate from MebibitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMebibitsPerSecond(double mebibitspersecond) -#else - public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) -#endif - { - decimal value = (decimal) mebibitspersecond; - return new BitRate(value, BitRateUnit.MebibitPerSecond); - } - - /// - /// Get BitRate from MebibytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMebibytesPerSecond(double mebibytespersecond) -#else - public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) -#endif - { - decimal value = (decimal) mebibytespersecond; - return new BitRate(value, BitRateUnit.MebibytePerSecond); - } - - /// - /// Get BitRate from MegabitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMegabitsPerSecond(double megabitspersecond) -#else - public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) -#endif - { - decimal value = (decimal) megabitspersecond; - return new BitRate(value, BitRateUnit.MegabitPerSecond); - } - - /// - /// Get BitRate from MegabytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMegabytesPerSecond(double megabytespersecond) -#else - public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) -#endif - { - decimal value = (decimal) megabytespersecond; - return new BitRate(value, BitRateUnit.MegabytePerSecond); - } - - /// - /// Get BitRate from PebibitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPebibitsPerSecond(double pebibitspersecond) -#else - public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) -#endif - { - decimal value = (decimal) pebibitspersecond; - return new BitRate(value, BitRateUnit.PebibitPerSecond); - } - - /// - /// Get BitRate from PebibytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPebibytesPerSecond(double pebibytespersecond) -#else - public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) -#endif - { - decimal value = (decimal) pebibytespersecond; - return new BitRate(value, BitRateUnit.PebibytePerSecond); - } - - /// - /// Get BitRate from PetabitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPetabitsPerSecond(double petabitspersecond) -#else - public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) -#endif - { - decimal value = (decimal) petabitspersecond; - return new BitRate(value, BitRateUnit.PetabitPerSecond); - } - - /// - /// Get BitRate from PetabytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPetabytesPerSecond(double petabytespersecond) -#else - public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) -#endif - { - decimal value = (decimal) petabytespersecond; - return new BitRate(value, BitRateUnit.PetabytePerSecond); - } - - /// - /// Get BitRate from TebibitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTebibitsPerSecond(double tebibitspersecond) -#else - public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) -#endif - { - decimal value = (decimal) tebibitspersecond; - return new BitRate(value, BitRateUnit.TebibitPerSecond); - } - - /// - /// Get BitRate from TebibytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTebibytesPerSecond(double tebibytespersecond) -#else - public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) -#endif - { - decimal value = (decimal) tebibytespersecond; - return new BitRate(value, BitRateUnit.TebibytePerSecond); - } - - /// - /// Get BitRate from TerabitsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTerabitsPerSecond(double terabitspersecond) -#else - public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) -#endif - { - decimal value = (decimal) terabitspersecond; - return new BitRate(value, BitRateUnit.TerabitPerSecond); - } - - /// - /// Get BitRate from TerabytesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTerabytesPerSecond(double terabytespersecond) -#else - public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) -#endif - { - decimal value = (decimal) terabytespersecond; - return new BitRate(value, BitRateUnit.TerabytePerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// BitRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static BitRate From(double value, BitRateUnit fromUnit) -#else - public static BitRate From(QuantityValue value, BitRateUnit fromUnit) -#endif - { - return new BitRate((decimal)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(BitRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is BitRate)) throw new ArgumentException("Expected type BitRate.", nameof(obj)); - - return CompareTo((BitRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(BitRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another BitRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BitRate other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BitRate. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BitRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this BitRate to another BitRate with the unit representation . - /// - /// A BitRate with the specified unit. - public BitRate ToUnit(BitRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new BitRate(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 decimal AsBaseUnit() - { - switch(Unit) - { - case BitRateUnit.BitPerSecond: return _value; - case BitRateUnit.BytePerSecond: return _value*8m; - case BitRateUnit.ExabitPerSecond: return (_value) * 1e18m; - case BitRateUnit.ExabytePerSecond: return (_value*8m) * 1e18m; - case BitRateUnit.ExbibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (_value) * (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (_value) * 1e9m; - case BitRateUnit.GigabytePerSecond: return (_value*8m) * 1e9m; - case BitRateUnit.KibibitPerSecond: return (_value) * 1024m; - case BitRateUnit.KibibytePerSecond: return (_value*8m) * 1024m; - case BitRateUnit.KilobitPerSecond: return (_value) * 1e3m; - case BitRateUnit.KilobytePerSecond: return (_value*8m) * 1e3m; - case BitRateUnit.MebibitPerSecond: return (_value) * (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (_value*8m) * (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (_value) * 1e6m; - case BitRateUnit.MegabytePerSecond: return (_value*8m) * 1e6m; - case BitRateUnit.PebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (_value) * 1e15m; - case BitRateUnit.PetabytePerSecond: return (_value*8m) * 1e15m; - case BitRateUnit.TebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (_value) * 1e12m; - case BitRateUnit.TerabytePerSecond: return (_value*8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(BitRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case BitRateUnit.BitPerSecond: return baseUnitValue; - case BitRateUnit.BytePerSecond: return baseUnitValue/8m; - case BitRateUnit.ExabitPerSecond: return (baseUnitValue) / 1e18m; - case BitRateUnit.ExabytePerSecond: return (baseUnitValue/8m) / 1e18m; - case BitRateUnit.ExbibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (baseUnitValue) / 1e9m; - case BitRateUnit.GigabytePerSecond: return (baseUnitValue/8m) / 1e9m; - case BitRateUnit.KibibitPerSecond: return (baseUnitValue) / 1024m; - case BitRateUnit.KibibytePerSecond: return (baseUnitValue/8m) / 1024m; - case BitRateUnit.KilobitPerSecond: return (baseUnitValue) / 1e3m; - case BitRateUnit.KilobytePerSecond: return (baseUnitValue/8m) / 1e3m; - case BitRateUnit.MebibitPerSecond: return (baseUnitValue) / (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (baseUnitValue) / 1e6m; - case BitRateUnit.MegabytePerSecond: return (baseUnitValue/8m) / 1e6m; - case BitRateUnit.PebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (baseUnitValue) / 1e15m; - case BitRateUnit.PetabytePerSecond: return (baseUnitValue/8m) / 1e15m; - case BitRateUnit.TebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (baseUnitValue) / 1e12m; - case BitRateUnit.TerabytePerSecond: return (baseUnitValue/8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 BitRate Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out BitRate result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BitRateUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out BitRateUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static BitRate ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out BitRate result) - { - result = default(BitRate); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static BitRateUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == BitRateUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BitRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out BitRateUnit unit) - { - unit = BitRateUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == BitRateUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(BitRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of BitRate - /// - public static BitRate MaxValue => new BitRate(decimal.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of BitRate - /// - public static BitRate MinValue => new BitRate(decimal.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => BitRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => BitRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs b/Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs deleted file mode 100644 index 0608d7e48d..0000000000 --- a/Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class BrakeSpecificFuelConsumption : IQuantity -#else - public partial struct BrakeSpecificFuelConsumption : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly BrakeSpecificFuelConsumptionUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static BrakeSpecificFuelConsumption() - { - BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - BrakeSpecificFuelConsumption(double numericValue, BrakeSpecificFuelConsumptionUnit unit) - { - if(unit == BrakeSpecificFuelConsumptionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.BrakeSpecificFuelConsumption; - - /// - /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. - /// - public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the BrakeSpecificFuelConsumption quantity. - /// - public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); - - /// - /// Get BrakeSpecificFuelConsumption in GramsPerKiloWattHour. - /// - public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - - /// - /// Get BrakeSpecificFuelConsumption in KilogramsPerJoule. - /// - public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - - /// - /// Get BrakeSpecificFuelConsumption in PoundsPerMechanicalHorsepowerHour. - /// - public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. - /// - public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(0, BaseUnit); - - /// - /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double gramsperkilowatthour) -#else - public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) -#endif - { - double value = (double) gramsperkilowatthour; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - } - - /// - /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double kilogramsperjoule) -#else - public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) -#endif - { - double value = (double) kilogramsperjoule; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - } - - /// - /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double poundspermechanicalhorsepowerhour) -#else - public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) -#endif - { - double value = (double) poundspermechanicalhorsepowerhour; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// BrakeSpecificFuelConsumption unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelConsumptionUnit fromUnit) -#else - public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) -#endif - { - return new BrakeSpecificFuelConsumption((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is BrakeSpecificFuelConsumption)) throw new ArgumentException("Expected type BrakeSpecificFuelConsumption.", nameof(obj)); - - return CompareTo((BrakeSpecificFuelConsumption)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(BrakeSpecificFuelConsumption other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another BrakeSpecificFuelConsumption within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BrakeSpecificFuelConsumption. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BrakeSpecificFuelConsumptionUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . - /// - /// A BrakeSpecificFuelConsumption with the specified unit. - public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new BrakeSpecificFuelConsumption(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 AsBaseUnit() - { - switch(Unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return _value/3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return _value; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return _value*1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(BrakeSpecificFuelConsumptionUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return baseUnitValue*3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return baseUnitValue; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return baseUnitValue/1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 BrakeSpecificFuelConsumption Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsumption result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static BrakeSpecificFuelConsumption ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out BrakeSpecificFuelConsumption result) - { - result = default(BrakeSpecificFuelConsumption); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static BrakeSpecificFuelConsumptionUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BrakeSpecificFuelConsumptionUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out BrakeSpecificFuelConsumptionUnit unit) - { - unit = BrakeSpecificFuelConsumptionUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == BrakeSpecificFuelConsumptionUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(BrakeSpecificFuelConsumptionUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of BrakeSpecificFuelConsumption - /// - public static BrakeSpecificFuelConsumption MaxValue => new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of BrakeSpecificFuelConsumption - /// - public static BrakeSpecificFuelConsumption MinValue => new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Capacitance.Common.g.cs b/Common/GeneratedCode/Quantities/Capacitance.Common.g.cs deleted file mode 100644 index 1fde587a73..0000000000 --- a/Common/GeneratedCode/Quantities/Capacitance.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Capacitance is the ability of a body to store an electric charge. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Capacitance : IQuantity -#else - public partial struct Capacitance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly CapacitanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Capacitance() - { - BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Capacitance(double numericValue, CapacitanceUnit unit) - { - if(unit == CapacitanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Capacitance; - - /// - /// The base unit of Capacitance, which is Farad. All conversions go via this value. - /// - public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Capacitance quantity. - /// - public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); - - /// - /// Get Capacitance in Farads. - /// - public double Farads => As(CapacitanceUnit.Farad); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Farad. - /// - public static Capacitance Zero => new Capacitance(0, BaseUnit); - - /// - /// Get Capacitance from Farads. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromFarads(double farads) -#else - public static Capacitance FromFarads(QuantityValue farads) -#endif - { - double value = (double) farads; - return new Capacitance(value, CapacitanceUnit.Farad); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Capacitance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Capacitance From(double value, CapacitanceUnit fromUnit) -#else - public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) -#endif - { - return new Capacitance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(CapacitanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Capacitance)) throw new ArgumentException("Expected type Capacitance.", nameof(obj)); - - return CompareTo((Capacitance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Capacitance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Capacitance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Capacitance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Capacitance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CapacitanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Capacitance to another Capacitance with the unit representation . - /// - /// A Capacitance with the specified unit. - public Capacitance ToUnit(CapacitanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Capacitance(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 AsBaseUnit() - { - switch(Unit) - { - case CapacitanceUnit.Farad: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(CapacitanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case CapacitanceUnit.Farad: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Capacitance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Capacitance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CapacitanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out CapacitanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Capacitance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Capacitance result) - { - result = default(Capacitance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static CapacitanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == CapacitanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized CapacitanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out CapacitanceUnit unit) - { - unit = CapacitanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == CapacitanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(CapacitanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Capacitance - /// - public static Capacitance MaxValue => new Capacitance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Capacitance - /// - public static Capacitance MinValue => new Capacitance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Capacitance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Capacitance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Density.Common.g.cs b/Common/GeneratedCode/Quantities/Density.Common.g.cs deleted file mode 100644 index dc2aee8589..0000000000 --- a/Common/GeneratedCode/Quantities/Density.Common.g.cs +++ /dev/null @@ -1,1351 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Density : IQuantity -#else - public partial struct Density : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Density() - { - BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Density(double numericValue, DensityUnit unit) - { - if(unit == DensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Density; - - /// - /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. - /// - public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Density quantity. - /// - public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); - - /// - /// Get Density in CentigramsPerDeciLiter. - /// - public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); - - /// - /// Get Density in CentigramsPerLiter. - /// - public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); - - /// - /// Get Density in CentigramsPerMilliliter. - /// - public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); - - /// - /// Get Density in DecigramsPerDeciLiter. - /// - public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); - - /// - /// Get Density in DecigramsPerLiter. - /// - public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); - - /// - /// Get Density in DecigramsPerMilliliter. - /// - public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); - - /// - /// Get Density in GramsPerCubicCentimeter. - /// - public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); - - /// - /// Get Density in GramsPerCubicMeter. - /// - public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); - - /// - /// Get Density in GramsPerCubicMillimeter. - /// - public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); - - /// - /// Get Density in GramsPerDeciLiter. - /// - public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); - - /// - /// Get Density in GramsPerLiter. - /// - public double GramsPerLiter => As(DensityUnit.GramPerLiter); - - /// - /// Get Density in GramsPerMilliliter. - /// - public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); - - /// - /// Get Density in KilogramsPerCubicCentimeter. - /// - public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); - - /// - /// Get Density in KilogramsPerCubicMeter. - /// - public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); - - /// - /// Get Density in KilogramsPerCubicMillimeter. - /// - public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); - - /// - /// Get Density in KilopoundsPerCubicFoot. - /// - public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); - - /// - /// Get Density in KilopoundsPerCubicInch. - /// - public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); - - /// - /// Get Density in MicrogramsPerDeciLiter. - /// - public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); - - /// - /// Get Density in MicrogramsPerLiter. - /// - public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); - - /// - /// Get Density in MicrogramsPerMilliliter. - /// - public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); - - /// - /// Get Density in MilligramsPerCubicMeter. - /// - public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); - - /// - /// Get Density in MilligramsPerDeciLiter. - /// - public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); - - /// - /// Get Density in MilligramsPerLiter. - /// - public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); - - /// - /// Get Density in MilligramsPerMilliliter. - /// - public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); - - /// - /// Get Density in NanogramsPerDeciLiter. - /// - public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); - - /// - /// Get Density in NanogramsPerLiter. - /// - public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); - - /// - /// Get Density in NanogramsPerMilliliter. - /// - public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); - - /// - /// Get Density in PicogramsPerDeciLiter. - /// - public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); - - /// - /// Get Density in PicogramsPerLiter. - /// - public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); - - /// - /// Get Density in PicogramsPerMilliliter. - /// - public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); - - /// - /// Get Density in PoundsPerCubicFoot. - /// - public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); - - /// - /// Get Density in PoundsPerCubicInch. - /// - public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); - - /// - /// Get Density in PoundsPerImperialGallon. - /// - public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); - - /// - /// Get Density in PoundsPerUSGallon. - /// - public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); - - /// - /// Get Density in SlugsPerCubicFoot. - /// - public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); - - /// - /// Get Density in TonnesPerCubicCentimeter. - /// - public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); - - /// - /// Get Density in TonnesPerCubicMeter. - /// - public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); - - /// - /// Get Density in TonnesPerCubicMillimeter. - /// - public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. - /// - public static Density Zero => new Density(0, BaseUnit); - - /// - /// Get Density from CentigramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerDeciLiter(double centigramsperdeciliter) -#else - public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) -#endif - { - double value = (double) centigramsperdeciliter; - return new Density(value, DensityUnit.CentigramPerDeciliter); - } - - /// - /// Get Density from CentigramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerLiter(double centigramsperliter) -#else - public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) -#endif - { - double value = (double) centigramsperliter; - return new Density(value, DensityUnit.CentigramPerLiter); - } - - /// - /// Get Density from CentigramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerMilliliter(double centigramspermilliliter) -#else - public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) -#endif - { - double value = (double) centigramspermilliliter; - return new Density(value, DensityUnit.CentigramPerMilliliter); - } - - /// - /// Get Density from DecigramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerDeciLiter(double decigramsperdeciliter) -#else - public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) -#endif - { - double value = (double) decigramsperdeciliter; - return new Density(value, DensityUnit.DecigramPerDeciliter); - } - - /// - /// Get Density from DecigramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerLiter(double decigramsperliter) -#else - public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) -#endif - { - double value = (double) decigramsperliter; - return new Density(value, DensityUnit.DecigramPerLiter); - } - - /// - /// Get Density from DecigramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerMilliliter(double decigramspermilliliter) -#else - public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) -#endif - { - double value = (double) decigramspermilliliter; - return new Density(value, DensityUnit.DecigramPerMilliliter); - } - - /// - /// Get Density from GramsPerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicCentimeter(double gramspercubiccentimeter) -#else - public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) -#endif - { - double value = (double) gramspercubiccentimeter; - return new Density(value, DensityUnit.GramPerCubicCentimeter); - } - - /// - /// Get Density from GramsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicMeter(double gramspercubicmeter) -#else - public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) -#endif - { - double value = (double) gramspercubicmeter; - return new Density(value, DensityUnit.GramPerCubicMeter); - } - - /// - /// Get Density from GramsPerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicMillimeter(double gramspercubicmillimeter) -#else - public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) -#endif - { - double value = (double) gramspercubicmillimeter; - return new Density(value, DensityUnit.GramPerCubicMillimeter); - } - - /// - /// Get Density from GramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerDeciLiter(double gramsperdeciliter) -#else - public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) -#endif - { - double value = (double) gramsperdeciliter; - return new Density(value, DensityUnit.GramPerDeciliter); - } - - /// - /// Get Density from GramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerLiter(double gramsperliter) -#else - public static Density FromGramsPerLiter(QuantityValue gramsperliter) -#endif - { - double value = (double) gramsperliter; - return new Density(value, DensityUnit.GramPerLiter); - } - - /// - /// Get Density from GramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerMilliliter(double gramspermilliliter) -#else - public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) -#endif - { - double value = (double) gramspermilliliter; - return new Density(value, DensityUnit.GramPerMilliliter); - } - - /// - /// Get Density from KilogramsPerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) -#else - public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) -#endif - { - double value = (double) kilogramspercubiccentimeter; - return new Density(value, DensityUnit.KilogramPerCubicCentimeter); - } - - /// - /// Get Density from KilogramsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicMeter(double kilogramspercubicmeter) -#else - public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) -#endif - { - double value = (double) kilogramspercubicmeter; - return new Density(value, DensityUnit.KilogramPerCubicMeter); - } - - /// - /// Get Density from KilogramsPerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) -#else - public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) -#endif - { - double value = (double) kilogramspercubicmillimeter; - return new Density(value, DensityUnit.KilogramPerCubicMillimeter); - } - - /// - /// Get Density from KilopoundsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) -#else - public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) -#endif - { - double value = (double) kilopoundspercubicfoot; - return new Density(value, DensityUnit.KilopoundPerCubicFoot); - } - - /// - /// Get Density from KilopoundsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilopoundsPerCubicInch(double kilopoundspercubicinch) -#else - public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) -#endif - { - double value = (double) kilopoundspercubicinch; - return new Density(value, DensityUnit.KilopoundPerCubicInch); - } - - /// - /// Get Density from MicrogramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerDeciLiter(double microgramsperdeciliter) -#else - public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) -#endif - { - double value = (double) microgramsperdeciliter; - return new Density(value, DensityUnit.MicrogramPerDeciliter); - } - - /// - /// Get Density from MicrogramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerLiter(double microgramsperliter) -#else - public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) -#endif - { - double value = (double) microgramsperliter; - return new Density(value, DensityUnit.MicrogramPerLiter); - } - - /// - /// Get Density from MicrogramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerMilliliter(double microgramspermilliliter) -#else - public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) -#endif - { - double value = (double) microgramspermilliliter; - return new Density(value, DensityUnit.MicrogramPerMilliliter); - } - - /// - /// Get Density from MilligramsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerCubicMeter(double milligramspercubicmeter) -#else - public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) -#endif - { - double value = (double) milligramspercubicmeter; - return new Density(value, DensityUnit.MilligramPerCubicMeter); - } - - /// - /// Get Density from MilligramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerDeciLiter(double milligramsperdeciliter) -#else - public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) -#endif - { - double value = (double) milligramsperdeciliter; - return new Density(value, DensityUnit.MilligramPerDeciliter); - } - - /// - /// Get Density from MilligramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerLiter(double milligramsperliter) -#else - public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) -#endif - { - double value = (double) milligramsperliter; - return new Density(value, DensityUnit.MilligramPerLiter); - } - - /// - /// Get Density from MilligramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerMilliliter(double milligramspermilliliter) -#else - public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) -#endif - { - double value = (double) milligramspermilliliter; - return new Density(value, DensityUnit.MilligramPerMilliliter); - } - - /// - /// Get Density from NanogramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerDeciLiter(double nanogramsperdeciliter) -#else - public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) -#endif - { - double value = (double) nanogramsperdeciliter; - return new Density(value, DensityUnit.NanogramPerDeciliter); - } - - /// - /// Get Density from NanogramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerLiter(double nanogramsperliter) -#else - public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) -#endif - { - double value = (double) nanogramsperliter; - return new Density(value, DensityUnit.NanogramPerLiter); - } - - /// - /// Get Density from NanogramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerMilliliter(double nanogramspermilliliter) -#else - public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) -#endif - { - double value = (double) nanogramspermilliliter; - return new Density(value, DensityUnit.NanogramPerMilliliter); - } - - /// - /// Get Density from PicogramsPerDeciLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerDeciLiter(double picogramsperdeciliter) -#else - public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) -#endif - { - double value = (double) picogramsperdeciliter; - return new Density(value, DensityUnit.PicogramPerDeciliter); - } - - /// - /// Get Density from PicogramsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerLiter(double picogramsperliter) -#else - public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) -#endif - { - double value = (double) picogramsperliter; - return new Density(value, DensityUnit.PicogramPerLiter); - } - - /// - /// Get Density from PicogramsPerMilliliter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerMilliliter(double picogramspermilliliter) -#else - public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) -#endif - { - double value = (double) picogramspermilliliter; - return new Density(value, DensityUnit.PicogramPerMilliliter); - } - - /// - /// Get Density from PoundsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicFoot(double poundspercubicfoot) -#else - public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) -#endif - { - double value = (double) poundspercubicfoot; - return new Density(value, DensityUnit.PoundPerCubicFoot); - } - - /// - /// Get Density from PoundsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicInch(double poundspercubicinch) -#else - public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) -#endif - { - double value = (double) poundspercubicinch; - return new Density(value, DensityUnit.PoundPerCubicInch); - } - - /// - /// Get Density from PoundsPerImperialGallon. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerImperialGallon(double poundsperimperialgallon) -#else - public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) -#endif - { - double value = (double) poundsperimperialgallon; - return new Density(value, DensityUnit.PoundPerImperialGallon); - } - - /// - /// Get Density from PoundsPerUSGallon. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerUSGallon(double poundsperusgallon) -#else - public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) -#endif - { - double value = (double) poundsperusgallon; - return new Density(value, DensityUnit.PoundPerUSGallon); - } - - /// - /// Get Density from SlugsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicFoot(double slugspercubicfoot) -#else - public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) -#endif - { - double value = (double) slugspercubicfoot; - return new Density(value, DensityUnit.SlugPerCubicFoot); - } - - /// - /// Get Density from TonnesPerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) -#else - public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) -#endif - { - double value = (double) tonnespercubiccentimeter; - return new Density(value, DensityUnit.TonnePerCubicCentimeter); - } - - /// - /// Get Density from TonnesPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicMeter(double tonnespercubicmeter) -#else - public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) -#endif - { - double value = (double) tonnespercubicmeter; - return new Density(value, DensityUnit.TonnePerCubicMeter); - } - - /// - /// Get Density from TonnesPerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) -#else - public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) -#endif - { - double value = (double) tonnespercubicmillimeter; - return new Density(value, DensityUnit.TonnePerCubicMillimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Density unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Density From(double value, DensityUnit fromUnit) -#else - public static Density From(QuantityValue value, DensityUnit fromUnit) -#endif - { - return new Density((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Density)) throw new ArgumentException("Expected type Density.", nameof(obj)); - - return CompareTo((Density)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Density other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Density within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Density other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Density. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Density to another Density with the unit representation . - /// - /// A Density with the specified unit. - public Density ToUnit(DensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Density(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 AsBaseUnit() - { - switch(Unit) - { - case DensityUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; - case DensityUnit.CentigramPerLiter: return (_value/1) * 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; - case DensityUnit.DecigramPerLiter: return (_value/1) * 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return _value/1e-3; - case DensityUnit.GramPerCubicMeter: return _value/1e3; - case DensityUnit.GramPerCubicMillimeter: return _value/1e-6; - case DensityUnit.GramPerDeciliter: return _value/1e-1; - case DensityUnit.GramPerLiter: return _value/1; - case DensityUnit.GramPerMilliliter: return _value/1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; - case DensityUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; - case DensityUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; - case DensityUnit.MicrogramPerLiter: return (_value/1) * 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; - case DensityUnit.MilligramPerLiter: return (_value/1) * 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; - case DensityUnit.NanogramPerLiter: return (_value/1) * 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; - case DensityUnit.PicogramPerLiter: return (_value/1) * 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; - case DensityUnit.PoundPerCubicFoot: return _value/0.062427961; - case DensityUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; - case DensityUnit.PoundPerImperialGallon: return _value*9.9776398e1; - case DensityUnit.PoundPerUSGallon: return _value*1.19826427e2; - case DensityUnit.SlugPerCubicFoot: return _value*515.378818; - case DensityUnit.TonnePerCubicCentimeter: return _value/1e-9; - case DensityUnit.TonnePerCubicMeter: return _value/0.001; - case DensityUnit.TonnePerCubicMillimeter: return _value/1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DensityUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; - case DensityUnit.CentigramPerLiter: return (baseUnitValue*1) / 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; - case DensityUnit.DecigramPerLiter: return (baseUnitValue*1) / 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; - case DensityUnit.GramPerCubicMeter: return baseUnitValue*1e3; - case DensityUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; - case DensityUnit.GramPerDeciliter: return baseUnitValue*1e-1; - case DensityUnit.GramPerLiter: return baseUnitValue*1; - case DensityUnit.GramPerMilliliter: return baseUnitValue*1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; - case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; - case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; - case DensityUnit.MicrogramPerLiter: return (baseUnitValue*1) / 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; - case DensityUnit.MilligramPerLiter: return (baseUnitValue*1) / 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; - case DensityUnit.NanogramPerLiter: return (baseUnitValue*1) / 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; - case DensityUnit.PicogramPerLiter: return (baseUnitValue*1) / 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; - case DensityUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; - case DensityUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; - case DensityUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; - case DensityUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; - case DensityUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; - case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; - case DensityUnit.TonnePerCubicMeter: return baseUnitValue*0.001; - case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Density Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Density result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out DensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Density ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Density result) - { - result = default(Density); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static DensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == DensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out DensityUnit unit) - { - unit = DensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == DensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(DensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Density - /// - public static Density MaxValue => new Density(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Density - /// - public static Density MinValue => new Density(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Density.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Density.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Duration.Common.g.cs b/Common/GeneratedCode/Quantities/Duration.Common.g.cs deleted file mode 100644 index 73439f778c..0000000000 --- a/Common/GeneratedCode/Quantities/Duration.Common.g.cs +++ /dev/null @@ -1,735 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Duration : IQuantity -#else - public partial struct Duration : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DurationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Duration() - { - BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Duration(double numericValue, DurationUnit unit) - { - if(unit == DurationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Duration; - - /// - /// The base unit of Duration, which is Second. All conversions go via this value. - /// - public static DurationUnit BaseUnit => DurationUnit.Second; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Duration quantity. - /// - public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); - - /// - /// Get Duration in Days. - /// - public double Days => As(DurationUnit.Day); - - /// - /// Get Duration in Hours. - /// - public double Hours => As(DurationUnit.Hour); - - /// - /// Get Duration in Microseconds. - /// - public double Microseconds => As(DurationUnit.Microsecond); - - /// - /// Get Duration in Milliseconds. - /// - public double Milliseconds => As(DurationUnit.Millisecond); - - /// - /// Get Duration in Minutes. - /// - public double Minutes => As(DurationUnit.Minute); - - /// - /// Get Duration in Months30. - /// - public double Months30 => As(DurationUnit.Month30); - - /// - /// Get Duration in Nanoseconds. - /// - public double Nanoseconds => As(DurationUnit.Nanosecond); - - /// - /// Get Duration in Seconds. - /// - public double Seconds => As(DurationUnit.Second); - - /// - /// Get Duration in Weeks. - /// - public double Weeks => As(DurationUnit.Week); - - /// - /// Get Duration in Years365. - /// - public double Years365 => As(DurationUnit.Year365); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Second. - /// - public static Duration Zero => new Duration(0, BaseUnit); - - /// - /// Get Duration from Days. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromDays(double days) -#else - public static Duration FromDays(QuantityValue days) -#endif - { - double value = (double) days; - return new Duration(value, DurationUnit.Day); - } - - /// - /// Get Duration from Hours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromHours(double hours) -#else - public static Duration FromHours(QuantityValue hours) -#endif - { - double value = (double) hours; - return new Duration(value, DurationUnit.Hour); - } - - /// - /// Get Duration from Microseconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMicroseconds(double microseconds) -#else - public static Duration FromMicroseconds(QuantityValue microseconds) -#endif - { - double value = (double) microseconds; - return new Duration(value, DurationUnit.Microsecond); - } - - /// - /// Get Duration from Milliseconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMilliseconds(double milliseconds) -#else - public static Duration FromMilliseconds(QuantityValue milliseconds) -#endif - { - double value = (double) milliseconds; - return new Duration(value, DurationUnit.Millisecond); - } - - /// - /// Get Duration from Minutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMinutes(double minutes) -#else - public static Duration FromMinutes(QuantityValue minutes) -#endif - { - double value = (double) minutes; - return new Duration(value, DurationUnit.Minute); - } - - /// - /// Get Duration from Months30. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMonths30(double months30) -#else - public static Duration FromMonths30(QuantityValue months30) -#endif - { - double value = (double) months30; - return new Duration(value, DurationUnit.Month30); - } - - /// - /// Get Duration from Nanoseconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromNanoseconds(double nanoseconds) -#else - public static Duration FromNanoseconds(QuantityValue nanoseconds) -#endif - { - double value = (double) nanoseconds; - return new Duration(value, DurationUnit.Nanosecond); - } - - /// - /// Get Duration from Seconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromSeconds(double seconds) -#else - public static Duration FromSeconds(QuantityValue seconds) -#endif - { - double value = (double) seconds; - return new Duration(value, DurationUnit.Second); - } - - /// - /// Get Duration from Weeks. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromWeeks(double weeks) -#else - public static Duration FromWeeks(QuantityValue weeks) -#endif - { - double value = (double) weeks; - return new Duration(value, DurationUnit.Week); - } - - /// - /// Get Duration from Years365. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromYears365(double years365) -#else - public static Duration FromYears365(QuantityValue years365) -#endif - { - double value = (double) years365; - return new Duration(value, DurationUnit.Year365); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Duration unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Duration From(double value, DurationUnit fromUnit) -#else - public static Duration From(QuantityValue value, DurationUnit fromUnit) -#endif - { - return new Duration((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DurationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Duration)) throw new ArgumentException("Expected type Duration.", nameof(obj)); - - return CompareTo((Duration)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Duration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Duration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Duration other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Duration. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DurationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Duration ToUnit(DurationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Duration(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 AsBaseUnit() - { - switch(Unit) - { - case DurationUnit.Day: return _value*24*3600; - case DurationUnit.Hour: return _value*3600; - case DurationUnit.Microsecond: return (_value) * 1e-6d; - case DurationUnit.Millisecond: return (_value) * 1e-3d; - case DurationUnit.Minute: return _value*60; - case DurationUnit.Month30: return _value*30*24*3600; - case DurationUnit.Nanosecond: return (_value) * 1e-9d; - case DurationUnit.Second: return _value; - case DurationUnit.Week: return _value*7*24*3600; - case DurationUnit.Year365: return _value*365*24*3600; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DurationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DurationUnit.Day: return baseUnitValue/(24*3600); - case DurationUnit.Hour: return baseUnitValue/3600; - case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; - case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; - case DurationUnit.Minute: return baseUnitValue/60; - case DurationUnit.Month30: return baseUnitValue/(30*24*3600); - case DurationUnit.Nanosecond: return (baseUnitValue) / 1e-9d; - case DurationUnit.Second: return baseUnitValue; - case DurationUnit.Week: return baseUnitValue/(7*24*3600); - case DurationUnit.Year365: return baseUnitValue/(365*24*3600); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Duration Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Duration result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DurationUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out DurationUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Duration ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Duration result) - { - result = default(Duration); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static DurationUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == DurationUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DurationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out DurationUnit unit) - { - unit = DurationUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == DurationUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(DurationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Duration - /// - public static Duration MaxValue => new Duration(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Duration - /// - public static Duration MinValue => new Duration(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Duration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Duration.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs b/Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs deleted file mode 100644 index 23979f9711..0000000000 --- a/Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs +++ /dev/null @@ -1,647 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class DynamicViscosity : IQuantity -#else - public partial struct DynamicViscosity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DynamicViscosityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static DynamicViscosity() - { - BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - DynamicViscosity(double numericValue, DynamicViscosityUnit unit) - { - if(unit == DynamicViscosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.DynamicViscosity; - - /// - /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. - /// - public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the DynamicViscosity quantity. - /// - public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); - - /// - /// Get DynamicViscosity in Centipoise. - /// - public double Centipoise => As(DynamicViscosityUnit.Centipoise); - - /// - /// Get DynamicViscosity in MicropascalSeconds. - /// - public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); - - /// - /// Get DynamicViscosity in MillipascalSeconds. - /// - public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); - - /// - /// Get DynamicViscosity in NewtonSecondsPerMeterSquared. - /// - public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); - - /// - /// Get DynamicViscosity in PascalSeconds. - /// - public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); - - /// - /// Get DynamicViscosity in Poise. - /// - public double Poise => As(DynamicViscosityUnit.Poise); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. - /// - public static DynamicViscosity Zero => new DynamicViscosity(0, BaseUnit); - - /// - /// Get DynamicViscosity from Centipoise. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromCentipoise(double centipoise) -#else - public static DynamicViscosity FromCentipoise(QuantityValue centipoise) -#endif - { - double value = (double) centipoise; - return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); - } - - /// - /// Get DynamicViscosity from MicropascalSeconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromMicropascalSeconds(double micropascalseconds) -#else - public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) -#endif - { - double value = (double) micropascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); - } - - /// - /// Get DynamicViscosity from MillipascalSeconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromMillipascalSeconds(double millipascalseconds) -#else - public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) -#endif - { - double value = (double) millipascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); - } - - /// - /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double newtonsecondspermetersquared) -#else - public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) -#endif - { - double value = (double) newtonsecondspermetersquared; - return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); - } - - /// - /// Get DynamicViscosity from PascalSeconds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPascalSeconds(double pascalseconds) -#else - public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) -#endif - { - double value = (double) pascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); - } - - /// - /// Get DynamicViscosity from Poise. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPoise(double poise) -#else - public static DynamicViscosity FromPoise(QuantityValue poise) -#endif - { - double value = (double) poise; - return new DynamicViscosity(value, DynamicViscosityUnit.Poise); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// DynamicViscosity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) -#else - public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) -#endif - { - return new DynamicViscosity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DynamicViscosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is DynamicViscosity)) throw new ArgumentException("Expected type DynamicViscosity.", nameof(obj)); - - return CompareTo((DynamicViscosity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(DynamicViscosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another DynamicViscosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current DynamicViscosity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DynamicViscosityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . - /// - /// A DynamicViscosity with the specified unit. - public DynamicViscosity ToUnit(DynamicViscosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new DynamicViscosity(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 AsBaseUnit() - { - switch(Unit) - { - case DynamicViscosityUnit.Centipoise: return (_value/10) * 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; - case DynamicViscosityUnit.PascalSecond: return _value; - case DynamicViscosityUnit.Poise: return _value/10; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DynamicViscosityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DynamicViscosityUnit.Centipoise: return (baseUnitValue*10) / 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; - case DynamicViscosityUnit.PascalSecond: return baseUnitValue; - case DynamicViscosityUnit.Poise: return baseUnitValue*10; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 DynamicViscosity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DynamicViscosityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static DynamicViscosity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out DynamicViscosity result) - { - result = default(DynamicViscosity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static DynamicViscosityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == DynamicViscosityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DynamicViscosityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out DynamicViscosityUnit unit) - { - unit = DynamicViscosityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == DynamicViscosityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(DynamicViscosityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of DynamicViscosity - /// - public static DynamicViscosity MaxValue => new DynamicViscosity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of DynamicViscosity - /// - public static DynamicViscosity MinValue => new DynamicViscosity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => DynamicViscosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs deleted file mode 100644 index 63a672f664..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricAdmittance : IQuantity -#else - public partial struct ElectricAdmittance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricAdmittanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricAdmittance() - { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricAdmittance(double numericValue, ElectricAdmittanceUnit unit) - { - if(unit == ElectricAdmittanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricAdmittance; - - /// - /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. - /// - public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricAdmittance quantity. - /// - public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricAdmittance in Microsiemens. - /// - public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); - - /// - /// Get ElectricAdmittance in Millisiemens. - /// - public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); - - /// - /// Get ElectricAdmittance in Nanosiemens. - /// - public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); - - /// - /// Get ElectricAdmittance in Siemens. - /// - public double Siemens => As(ElectricAdmittanceUnit.Siemens); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. - /// - public static ElectricAdmittance Zero => new ElectricAdmittance(0, BaseUnit); - - /// - /// Get ElectricAdmittance from Microsiemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromMicrosiemens(double microsiemens) -#else - public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) -#endif - { - double value = (double) microsiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); - } - - /// - /// Get ElectricAdmittance from Millisiemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromMillisiemens(double millisiemens) -#else - public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) -#endif - { - double value = (double) millisiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); - } - - /// - /// Get ElectricAdmittance from Nanosiemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromNanosiemens(double nanosiemens) -#else - public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) -#endif - { - double value = (double) nanosiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); - } - - /// - /// Get ElectricAdmittance from Siemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromSiemens(double siemens) -#else - public static ElectricAdmittance FromSiemens(QuantityValue siemens) -#endif - { - double value = (double) siemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricAdmittance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromUnit) -#else - public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) -#endif - { - return new ElectricAdmittance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricAdmittanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricAdmittance)) throw new ArgumentException("Expected type ElectricAdmittance.", nameof(obj)); - - return CompareTo((ElectricAdmittance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricAdmittance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricAdmittance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricAdmittance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricAdmittanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . - /// - /// A ElectricAdmittance with the specified unit. - public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricAdmittance(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (_value) * 1e-9d; - case ElectricAdmittanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricAdmittanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (baseUnitValue) / 1e-9d; - case ElectricAdmittanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricAdmittance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricAdmittance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricAdmittanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricAdmittance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricAdmittance result) - { - result = default(ElectricAdmittance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricAdmittanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricAdmittanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricAdmittanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricAdmittanceUnit unit) - { - unit = ElectricAdmittanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricAdmittanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricAdmittanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricAdmittance - /// - public static ElectricAdmittance MaxValue => new ElectricAdmittance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricAdmittance - /// - public static ElectricAdmittance MinValue => new ElectricAdmittance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricAdmittance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs deleted file mode 100644 index 5dbfebef04..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCharge : IQuantity -#else - public partial struct ElectricCharge : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricChargeUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCharge() - { - BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCharge(double numericValue, ElectricChargeUnit unit) - { - if(unit == ElectricChargeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCharge; - - /// - /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. - /// - public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCharge quantity. - /// - public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCharge in Coulombs. - /// - public double Coulombs => As(ElectricChargeUnit.Coulomb); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. - /// - public static ElectricCharge Zero => new ElectricCharge(0, BaseUnit); - - /// - /// Get ElectricCharge from Coulombs. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromCoulombs(double coulombs) -#else - public static ElectricCharge FromCoulombs(QuantityValue coulombs) -#endif - { - double value = (double) coulombs; - return new ElectricCharge(value, ElectricChargeUnit.Coulomb); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCharge unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) -#else - public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) -#endif - { - return new ElectricCharge((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCharge)) throw new ArgumentException("Expected type ElectricCharge.", nameof(obj)); - - return CompareTo((ElectricCharge)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCharge other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCharge within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCharge other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCharge. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCharge to another ElectricCharge with the unit representation . - /// - /// A ElectricCharge with the specified unit. - public ElectricCharge ToUnit(ElectricChargeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCharge(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricChargeUnit.Coulomb: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricChargeUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricChargeUnit.Coulomb: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricCharge Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCharge result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricChargeUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricCharge ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCharge result) - { - result = default(ElectricCharge); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricChargeUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricChargeUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricChargeUnit unit) - { - unit = ElectricChargeUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricChargeUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricChargeUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCharge - /// - public static ElectricCharge MaxValue => new ElectricCharge(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCharge - /// - public static ElectricCharge MinValue => new ElectricCharge(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCharge.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs deleted file mode 100644 index 6cb2bad778..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, charge density is a measure of the amount of electric charge per unit length, surface area, or volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricChargeDensity : IQuantity -#else - public partial struct ElectricChargeDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricChargeDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricChargeDensity() - { - BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricChargeDensity(double numericValue, ElectricChargeDensityUnit unit) - { - if(unit == ElectricChargeDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricChargeDensity; - - /// - /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. - /// - public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricChargeDensity quantity. - /// - public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricChargeDensity in CoulombsPerCubicMeter. - /// - public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. - /// - public static ElectricChargeDensity Zero => new ElectricChargeDensity(0, BaseUnit); - - /// - /// Get ElectricChargeDensity from CoulombsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricChargeDensity FromCoulombsPerCubicMeter(double coulombspercubicmeter) -#else - public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) -#endif - { - double value = (double) coulombspercubicmeter; - return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricChargeDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit fromUnit) -#else - public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) -#endif - { - return new ElectricChargeDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricChargeDensity)) throw new ArgumentException("Expected type ElectricChargeDensity.", nameof(obj)); - - return CompareTo((ElectricChargeDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricChargeDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricChargeDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricChargeDensity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation . - /// - /// A ElectricChargeDensity with the specified unit. - public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricChargeDensity(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricChargeDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricChargeDensity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeDensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricChargeDensity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricChargeDensity result) - { - result = default(ElectricChargeDensity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricChargeDensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricChargeDensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricChargeDensityUnit unit) - { - unit = ElectricChargeDensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricChargeDensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricChargeDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricChargeDensity - /// - public static ElectricChargeDensity MaxValue => new ElectricChargeDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricChargeDensity - /// - public static ElectricChargeDensity MinValue => new ElectricChargeDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricChargeDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs deleted file mode 100644 index 56d39d998a..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricConductance : IQuantity -#else - public partial struct ElectricConductance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricConductanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricConductance() - { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricConductance(double numericValue, ElectricConductanceUnit unit) - { - if(unit == ElectricConductanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricConductance; - - /// - /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. - /// - public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricConductance quantity. - /// - public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricConductance in Microsiemens. - /// - public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); - - /// - /// Get ElectricConductance in Millisiemens. - /// - public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); - - /// - /// Get ElectricConductance in Siemens. - /// - public double Siemens => As(ElectricConductanceUnit.Siemens); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. - /// - public static ElectricConductance Zero => new ElectricConductance(0, BaseUnit); - - /// - /// Get ElectricConductance from Microsiemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromMicrosiemens(double microsiemens) -#else - public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) -#endif - { - double value = (double) microsiemens; - return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); - } - - /// - /// Get ElectricConductance from Millisiemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromMillisiemens(double millisiemens) -#else - public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) -#endif - { - double value = (double) millisiemens; - return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); - } - - /// - /// Get ElectricConductance from Siemens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromSiemens(double siemens) -#else - public static ElectricConductance FromSiemens(QuantityValue siemens) -#endif - { - double value = (double) siemens; - return new ElectricConductance(value, ElectricConductanceUnit.Siemens); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricConductance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricConductance From(double value, ElectricConductanceUnit fromUnit) -#else - public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) -#endif - { - return new ElectricConductance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricConductanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricConductance)) throw new ArgumentException("Expected type ElectricConductance.", nameof(obj)); - - return CompareTo((ElectricConductance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricConductance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricConductance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricConductance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricConductance to another ElectricConductance with the unit representation . - /// - /// A ElectricConductance with the specified unit. - public ElectricConductance ToUnit(ElectricConductanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricConductance(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricConductanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricConductanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricConductanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricConductanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricConductanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricConductance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricConductance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricConductance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricConductance result) - { - result = default(ElectricConductance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricConductanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricConductanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricConductanceUnit unit) - { - unit = ElectricConductanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricConductanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricConductanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricConductance - /// - public static ElectricConductance MaxValue => new ElectricConductance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricConductance - /// - public static ElectricConductance MinValue => new ElectricConductance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricConductance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs deleted file mode 100644 index b1079413da..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricConductivity : IQuantity -#else - public partial struct ElectricConductivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricConductivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricConductivity() - { - BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricConductivity(double numericValue, ElectricConductivityUnit unit) - { - if(unit == ElectricConductivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricConductivity; - - /// - /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. - /// - public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricConductivity quantity. - /// - public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricConductivity in SiemensPerMeter. - /// - public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. - /// - public static ElectricConductivity Zero => new ElectricConductivity(0, BaseUnit); - - /// - /// Get ElectricConductivity from SiemensPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromSiemensPerMeter(double siemenspermeter) -#else - public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) -#endif - { - double value = (double) siemenspermeter; - return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricConductivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricConductivity From(double value, ElectricConductivityUnit fromUnit) -#else - public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) -#endif - { - return new ElectricConductivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricConductivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricConductivity)) throw new ArgumentException("Expected type ElectricConductivity.", nameof(obj)); - - return CompareTo((ElectricConductivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricConductivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricConductivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricConductivity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductivity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation . - /// - /// A ElectricConductivity with the specified unit. - public ElectricConductivity ToUnit(ElectricConductivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricConductivity(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricConductivityUnit.SiemensPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricConductivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricConductivity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricConductivity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductivityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricConductivity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricConductivity result) - { - result = default(ElectricConductivity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricConductivityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricConductivityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricConductivityUnit unit) - { - unit = ElectricConductivityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricConductivityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricConductivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricConductivity - /// - public static ElectricConductivity MaxValue => new ElectricConductivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricConductivity - /// - public static ElectricConductivity MinValue => new ElectricConductivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricConductivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs deleted file mode 100644 index c05dd17d91..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCurrent : IQuantity -#else - public partial struct ElectricCurrent : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCurrent() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCurrent(double numericValue, ElectricCurrentUnit unit) - { - if(unit == ElectricCurrentUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCurrent; - - /// - /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. - /// - public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCurrent quantity. - /// - public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCurrent in Amperes. - /// - public double Amperes => As(ElectricCurrentUnit.Ampere); - - /// - /// Get ElectricCurrent in Centiamperes. - /// - public double Centiamperes => As(ElectricCurrentUnit.Centiampere); - - /// - /// Get ElectricCurrent in Kiloamperes. - /// - public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); - - /// - /// Get ElectricCurrent in Megaamperes. - /// - public double Megaamperes => As(ElectricCurrentUnit.Megaampere); - - /// - /// Get ElectricCurrent in Microamperes. - /// - public double Microamperes => As(ElectricCurrentUnit.Microampere); - - /// - /// Get ElectricCurrent in Milliamperes. - /// - public double Milliamperes => As(ElectricCurrentUnit.Milliampere); - - /// - /// Get ElectricCurrent in Nanoamperes. - /// - public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); - - /// - /// Get ElectricCurrent in Picoamperes. - /// - public double Picoamperes => As(ElectricCurrentUnit.Picoampere); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. - /// - public static ElectricCurrent Zero => new ElectricCurrent(0, BaseUnit); - - /// - /// Get ElectricCurrent from Amperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromAmperes(double amperes) -#else - public static ElectricCurrent FromAmperes(QuantityValue amperes) -#endif - { - double value = (double) amperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); - } - - /// - /// Get ElectricCurrent from Centiamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromCentiamperes(double centiamperes) -#else - public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) -#endif - { - double value = (double) centiamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); - } - - /// - /// Get ElectricCurrent from Kiloamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromKiloamperes(double kiloamperes) -#else - public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) -#endif - { - double value = (double) kiloamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); - } - - /// - /// Get ElectricCurrent from Megaamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMegaamperes(double megaamperes) -#else - public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) -#endif - { - double value = (double) megaamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); - } - - /// - /// Get ElectricCurrent from Microamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMicroamperes(double microamperes) -#else - public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) -#endif - { - double value = (double) microamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); - } - - /// - /// Get ElectricCurrent from Milliamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMilliamperes(double milliamperes) -#else - public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) -#endif - { - double value = (double) milliamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); - } - - /// - /// Get ElectricCurrent from Nanoamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromNanoamperes(double nanoamperes) -#else - public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) -#endif - { - double value = (double) nanoamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); - } - - /// - /// Get ElectricCurrent from Picoamperes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromPicoamperes(double picoamperes) -#else - public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) -#endif - { - double value = (double) picoamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrent unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) -#else - public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) -#endif - { - return new ElectricCurrent((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCurrent)) throw new ArgumentException("Expected type ElectricCurrent.", nameof(obj)); - - return CompareTo((ElectricCurrent)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCurrent other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCurrent within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrent other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrent. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation . - /// - /// A ElectricCurrent with the specified unit. - public ElectricCurrent ToUnit(ElectricCurrentUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrent(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentUnit.Ampere: return _value; - case ElectricCurrentUnit.Centiampere: return (_value) * 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (_value) * 1e3d; - case ElectricCurrentUnit.Megaampere: return (_value) * 1e6d; - case ElectricCurrentUnit.Microampere: return (_value) * 1e-6d; - case ElectricCurrentUnit.Milliampere: return (_value) * 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (_value) * 1e-9d; - case ElectricCurrentUnit.Picoampere: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentUnit.Ampere: return baseUnitValue; - case ElectricCurrentUnit.Centiampere: return (baseUnitValue) / 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (baseUnitValue) / 1e3d; - case ElectricCurrentUnit.Megaampere: return (baseUnitValue) / 1e6d; - case ElectricCurrentUnit.Microampere: return (baseUnitValue) / 1e-6d; - case ElectricCurrentUnit.Milliampere: return (baseUnitValue) / 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (baseUnitValue) / 1e-9d; - case ElectricCurrentUnit.Picoampere: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricCurrent Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricCurrent ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrent result) - { - result = default(ElectricCurrent); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricCurrentUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricCurrentUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricCurrentUnit unit) - { - unit = ElectricCurrentUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricCurrentUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricCurrentUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCurrent - /// - public static ElectricCurrent MaxValue => new ElectricCurrent(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCurrent - /// - public static ElectricCurrent MinValue => new ElectricCurrent(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCurrent.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs deleted file mode 100644 index 2bb80eac60..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, current density is the electric current per unit area of cross section. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCurrentDensity : IQuantity -#else - public partial struct ElectricCurrentDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCurrentDensity() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCurrentDensity(double numericValue, ElectricCurrentDensityUnit unit) - { - if(unit == ElectricCurrentDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCurrentDensity; - - /// - /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. - /// - public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCurrentDensity quantity. - /// - public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCurrentDensity in AmperesPerSquareMeter. - /// - public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. - /// - public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(0, BaseUnit); - - /// - /// Get ElectricCurrentDensity from AmperesPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentDensity FromAmperesPerSquareMeter(double amperespersquaremeter) -#else - public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) -#endif - { - double value = (double) amperespersquaremeter; - return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrentDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUnit fromUnit) -#else - public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) -#endif - { - return new ElectricCurrentDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCurrentDensity)) throw new ArgumentException("Expected type ElectricCurrentDensity.", nameof(obj)); - - return CompareTo((ElectricCurrentDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCurrentDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCurrentDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentDensity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation . - /// - /// A ElectricCurrentDensity with the specified unit. - public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrentDensity(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricCurrentDensity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentDensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricCurrentDensity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrentDensity result) - { - result = default(ElectricCurrentDensity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricCurrentDensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricCurrentDensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricCurrentDensityUnit unit) - { - unit = ElectricCurrentDensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricCurrentDensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricCurrentDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCurrentDensity - /// - public static ElectricCurrentDensity MaxValue => new ElectricCurrentDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCurrentDensity - /// - public static ElectricCurrentDensity MinValue => new ElectricCurrentDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCurrentDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs deleted file mode 100644 index 625f5f3f12..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, the current gradient describes how the current changes in time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCurrentGradient : IQuantity -#else - public partial struct ElectricCurrentGradient : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentGradientUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCurrentGradient() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCurrentGradient(double numericValue, ElectricCurrentGradientUnit unit) - { - if(unit == ElectricCurrentGradientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCurrentGradient; - - /// - /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. - /// - public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCurrentGradient quantity. - /// - public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCurrentGradient in AmperesPerSecond. - /// - public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. - /// - public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(0, BaseUnit); - - /// - /// Get ElectricCurrentGradient from AmperesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentGradient FromAmperesPerSecond(double amperespersecond) -#else - public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) -#endif - { - double value = (double) amperespersecond; - return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrentGradient unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrentGradient From(double value, ElectricCurrentGradientUnit fromUnit) -#else - public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) -#endif - { - return new ElectricCurrentGradient((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentGradientUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCurrentGradient)) throw new ArgumentException("Expected type ElectricCurrentGradient.", nameof(obj)); - - return CompareTo((ElectricCurrentGradient)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCurrentGradient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCurrentGradient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentGradient. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentGradientUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation . - /// - /// A ElectricCurrentGradient with the specified unit. - public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrentGradient(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentGradientUnit.AmperePerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentGradientUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricCurrentGradient Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentGradientUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricCurrentGradient ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrentGradient result) - { - result = default(ElectricCurrentGradient); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricCurrentGradientUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricCurrentGradientUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentGradientUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricCurrentGradientUnit unit) - { - unit = ElectricCurrentGradientUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricCurrentGradientUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricCurrentGradientUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCurrentGradient - /// - public static ElectricCurrentGradient MaxValue => new ElectricCurrentGradient(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCurrentGradient - /// - public static ElectricCurrentGradient MinValue => new ElectricCurrentGradient(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCurrentGradient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricField.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricField.Common.g.cs deleted file mode 100644 index 58e01b2c4b..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricField.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricField : IQuantity -#else - public partial struct ElectricField : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricFieldUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricField() - { - BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricField(double numericValue, ElectricFieldUnit unit) - { - if(unit == ElectricFieldUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricField; - - /// - /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. - /// - public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricField quantity. - /// - public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); - - /// - /// Get ElectricField in VoltsPerMeter. - /// - public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. - /// - public static ElectricField Zero => new ElectricField(0, BaseUnit); - - /// - /// Get ElectricField from VoltsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricField FromVoltsPerMeter(double voltspermeter) -#else - public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) -#endif - { - double value = (double) voltspermeter; - return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricField unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricField From(double value, ElectricFieldUnit fromUnit) -#else - public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) -#endif - { - return new ElectricField((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricFieldUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricField)) throw new ArgumentException("Expected type ElectricField.", nameof(obj)); - - return CompareTo((ElectricField)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricField other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricField within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricField other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricField. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricFieldUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricField to another ElectricField with the unit representation . - /// - /// A ElectricField with the specified unit. - public ElectricField ToUnit(ElectricFieldUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricField(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricFieldUnit.VoltPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricFieldUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricFieldUnit.VoltPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricField Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricField result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricFieldUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricFieldUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricField ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricField result) - { - result = default(ElectricField); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricFieldUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricFieldUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricFieldUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricFieldUnit unit) - { - unit = ElectricFieldUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricFieldUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricFieldUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricField - /// - public static ElectricField MaxValue => new ElectricField(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricField - /// - public static ElectricField MinValue => new ElectricField(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricField.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricField.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs deleted file mode 100644 index 2e5b239d35..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Inductance is a property of an electrical conductor which opposes a change in current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricInductance : IQuantity -#else - public partial struct ElectricInductance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricInductanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricInductance() - { - BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricInductance(double numericValue, ElectricInductanceUnit unit) - { - if(unit == ElectricInductanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricInductance; - - /// - /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. - /// - public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricInductance quantity. - /// - public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricInductance in Henries. - /// - public double Henries => As(ElectricInductanceUnit.Henry); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Henry. - /// - public static ElectricInductance Zero => new ElectricInductance(0, BaseUnit); - - /// - /// Get ElectricInductance from Henries. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromHenries(double henries) -#else - public static ElectricInductance FromHenries(QuantityValue henries) -#endif - { - double value = (double) henries; - return new ElectricInductance(value, ElectricInductanceUnit.Henry); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricInductance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricInductance From(double value, ElectricInductanceUnit fromUnit) -#else - public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) -#endif - { - return new ElectricInductance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricInductanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricInductance)) throw new ArgumentException("Expected type ElectricInductance.", nameof(obj)); - - return CompareTo((ElectricInductance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricInductance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricInductance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricInductance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricInductance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricInductanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricInductance to another ElectricInductance with the unit representation . - /// - /// A ElectricInductance with the specified unit. - public ElectricInductance ToUnit(ElectricInductanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricInductance(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricInductanceUnit.Henry: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricInductanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricInductanceUnit.Henry: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricInductance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricInductance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricInductanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricInductance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricInductance result) - { - result = default(ElectricInductance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricInductanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricInductanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricInductanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricInductanceUnit unit) - { - unit = ElectricInductanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricInductanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricInductanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricInductance - /// - public static ElectricInductance MaxValue => new ElectricInductance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricInductance - /// - public static ElectricInductance MinValue => new ElectricInductance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricInductance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs deleted file mode 100644 index 36d1bc9933..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs +++ /dev/null @@ -1,625 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricPotential : IQuantity -#else - public partial struct ElectricPotential : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricPotential() - { - BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricPotential(double numericValue, ElectricPotentialUnit unit) - { - if(unit == ElectricPotentialUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricPotential; - - /// - /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. - /// - public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricPotential quantity. - /// - public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); - - /// - /// Get ElectricPotential in Kilovolts. - /// - public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); - - /// - /// Get ElectricPotential in Megavolts. - /// - public double Megavolts => As(ElectricPotentialUnit.Megavolt); - - /// - /// Get ElectricPotential in Microvolts. - /// - public double Microvolts => As(ElectricPotentialUnit.Microvolt); - - /// - /// Get ElectricPotential in Millivolts. - /// - public double Millivolts => As(ElectricPotentialUnit.Millivolt); - - /// - /// Get ElectricPotential in Volts. - /// - public double Volts => As(ElectricPotentialUnit.Volt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Volt. - /// - public static ElectricPotential Zero => new ElectricPotential(0, BaseUnit); - - /// - /// Get ElectricPotential from Kilovolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromKilovolts(double kilovolts) -#else - public static ElectricPotential FromKilovolts(QuantityValue kilovolts) -#endif - { - double value = (double) kilovolts; - return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); - } - - /// - /// Get ElectricPotential from Megavolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMegavolts(double megavolts) -#else - public static ElectricPotential FromMegavolts(QuantityValue megavolts) -#endif - { - double value = (double) megavolts; - return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); - } - - /// - /// Get ElectricPotential from Microvolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMicrovolts(double microvolts) -#else - public static ElectricPotential FromMicrovolts(QuantityValue microvolts) -#endif - { - double value = (double) microvolts; - return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); - } - - /// - /// Get ElectricPotential from Millivolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMillivolts(double millivolts) -#else - public static ElectricPotential FromMillivolts(QuantityValue millivolts) -#endif - { - double value = (double) millivolts; - return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); - } - - /// - /// Get ElectricPotential from Volts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromVolts(double volts) -#else - public static ElectricPotential FromVolts(QuantityValue volts) -#endif - { - double value = (double) volts; - return new ElectricPotential(value, ElectricPotentialUnit.Volt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotential unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotential From(double value, ElectricPotentialUnit fromUnit) -#else - public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) -#endif - { - return new ElectricPotential((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricPotential)) throw new ArgumentException("Expected type ElectricPotential.", nameof(obj)); - - return CompareTo((ElectricPotential)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricPotential other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotential within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotential other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotential. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotential to another ElectricPotential with the unit representation . - /// - /// A ElectricPotential with the specified unit. - public ElectricPotential ToUnit(ElectricPotentialUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotential(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialUnit.Kilovolt: return (_value) * 1e3d; - case ElectricPotentialUnit.Megavolt: return (_value) * 1e6d; - case ElectricPotentialUnit.Microvolt: return (_value) * 1e-6d; - case ElectricPotentialUnit.Millivolt: return (_value) * 1e-3d; - case ElectricPotentialUnit.Volt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialUnit.Kilovolt: return (baseUnitValue) / 1e3d; - case ElectricPotentialUnit.Megavolt: return (baseUnitValue) / 1e6d; - case ElectricPotentialUnit.Microvolt: return (baseUnitValue) / 1e-6d; - case ElectricPotentialUnit.Millivolt: return (baseUnitValue) / 1e-3d; - case ElectricPotentialUnit.Volt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricPotential Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotential result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricPotential ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotential result) - { - result = default(ElectricPotential); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricPotentialUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricPotentialUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricPotentialUnit unit) - { - unit = ElectricPotentialUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricPotentialUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricPotentialUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricPotential - /// - public static ElectricPotential MaxValue => new ElectricPotential(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricPotential - /// - public static ElectricPotential MinValue => new ElectricPotential(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricPotential.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs deleted file mode 100644 index 25aece9384..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs +++ /dev/null @@ -1,624 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Electric Potential of a system known to use Alternating Current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricPotentialAc : IQuantity -#else - public partial struct ElectricPotentialAc : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialAcUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricPotentialAc() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricPotentialAc(double numericValue, ElectricPotentialAcUnit unit) - { - if(unit == ElectricPotentialAcUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricPotentialAc; - - /// - /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. - /// - public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricPotentialAc quantity. - /// - public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); - - /// - /// Get ElectricPotentialAc in KilovoltsAc. - /// - public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); - - /// - /// Get ElectricPotentialAc in MegavoltsAc. - /// - public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); - - /// - /// Get ElectricPotentialAc in MicrovoltsAc. - /// - public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); - - /// - /// Get ElectricPotentialAc in MillivoltsAc. - /// - public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); - - /// - /// Get ElectricPotentialAc in VoltsAc. - /// - public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. - /// - public static ElectricPotentialAc Zero => new ElectricPotentialAc(0, BaseUnit); - - /// - /// Get ElectricPotentialAc from KilovoltsAc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromKilovoltsAc(double kilovoltsac) -#else - public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) -#endif - { - double value = (double) kilovoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); - } - - /// - /// Get ElectricPotentialAc from MegavoltsAc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMegavoltsAc(double megavoltsac) -#else - public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) -#endif - { - double value = (double) megavoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); - } - - /// - /// Get ElectricPotentialAc from MicrovoltsAc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMicrovoltsAc(double microvoltsac) -#else - public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) -#endif - { - double value = (double) microvoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); - } - - /// - /// Get ElectricPotentialAc from MillivoltsAc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMillivoltsAc(double millivoltsac) -#else - public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) -#endif - { - double value = (double) millivoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); - } - - /// - /// Get ElectricPotentialAc from VoltsAc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromVoltsAc(double voltsac) -#else - public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) -#endif - { - double value = (double) voltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialAc unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fromUnit) -#else - public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) -#endif - { - return new ElectricPotentialAc((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialAcUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricPotentialAc)) throw new ArgumentException("Expected type ElectricPotentialAc.", nameof(obj)); - - return CompareTo((ElectricPotentialAc)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricPotentialAc other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotentialAc within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialAc. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialAcUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation . - /// - /// A ElectricPotentialAc with the specified unit. - public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialAc(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (_value) * 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (_value) * 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (_value) * 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (_value) * 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialAcUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (baseUnitValue) / 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (baseUnitValue) / 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricPotentialAc Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialAcUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricPotentialAc ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialAc result) - { - result = default(ElectricPotentialAc); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricPotentialAcUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricPotentialAcUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialAcUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricPotentialAcUnit unit) - { - unit = ElectricPotentialAcUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricPotentialAcUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricPotentialAcUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricPotentialAc - /// - public static ElectricPotentialAc MaxValue => new ElectricPotentialAc(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricPotentialAc - /// - public static ElectricPotentialAc MinValue => new ElectricPotentialAc(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricPotentialAc.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs deleted file mode 100644 index 1d2005ec42..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs +++ /dev/null @@ -1,624 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Electric Potential of a system known to use Direct Current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricPotentialDc : IQuantity -#else - public partial struct ElectricPotentialDc : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialDcUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricPotentialDc() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricPotentialDc(double numericValue, ElectricPotentialDcUnit unit) - { - if(unit == ElectricPotentialDcUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricPotentialDc; - - /// - /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. - /// - public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricPotentialDc quantity. - /// - public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); - - /// - /// Get ElectricPotentialDc in KilovoltsDc. - /// - public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); - - /// - /// Get ElectricPotentialDc in MegavoltsDc. - /// - public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); - - /// - /// Get ElectricPotentialDc in MicrovoltsDc. - /// - public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); - - /// - /// Get ElectricPotentialDc in MillivoltsDc. - /// - public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); - - /// - /// Get ElectricPotentialDc in VoltsDc. - /// - public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. - /// - public static ElectricPotentialDc Zero => new ElectricPotentialDc(0, BaseUnit); - - /// - /// Get ElectricPotentialDc from KilovoltsDc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromKilovoltsDc(double kilovoltsdc) -#else - public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) -#endif - { - double value = (double) kilovoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); - } - - /// - /// Get ElectricPotentialDc from MegavoltsDc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMegavoltsDc(double megavoltsdc) -#else - public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) -#endif - { - double value = (double) megavoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); - } - - /// - /// Get ElectricPotentialDc from MicrovoltsDc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMicrovoltsDc(double microvoltsdc) -#else - public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) -#endif - { - double value = (double) microvoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); - } - - /// - /// Get ElectricPotentialDc from MillivoltsDc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMillivoltsDc(double millivoltsdc) -#else - public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) -#endif - { - double value = (double) millivoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); - } - - /// - /// Get ElectricPotentialDc from VoltsDc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromVoltsDc(double voltsdc) -#else - public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) -#endif - { - double value = (double) voltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialDc unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fromUnit) -#else - public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) -#endif - { - return new ElectricPotentialDc((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialDcUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricPotentialDc)) throw new ArgumentException("Expected type ElectricPotentialDc.", nameof(obj)); - - return CompareTo((ElectricPotentialDc)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricPotentialDc other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotentialDc within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialDc other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialDc. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialDcUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation . - /// - /// A ElectricPotentialDc with the specified unit. - public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialDc(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (_value) * 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (_value) * 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (_value) * 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (_value) * 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialDcUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (baseUnitValue) / 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (baseUnitValue) / 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricPotentialDc Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialDcUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricPotentialDc ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialDc result) - { - result = default(ElectricPotentialDc); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricPotentialDcUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricPotentialDcUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialDcUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricPotentialDcUnit unit) - { - unit = ElectricPotentialDcUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricPotentialDcUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricPotentialDcUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricPotentialDc - /// - public static ElectricPotentialDc MaxValue => new ElectricPotentialDc(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricPotentialDc - /// - public static ElectricPotentialDc MinValue => new ElectricPotentialDc(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricPotentialDc.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs deleted file mode 100644 index 45f27e3218..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricResistance : IQuantity -#else - public partial struct ElectricResistance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricResistanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricResistance() - { - BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricResistance(double numericValue, ElectricResistanceUnit unit) - { - if(unit == ElectricResistanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricResistance; - - /// - /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. - /// - public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricResistance quantity. - /// - public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricResistance in Kiloohms. - /// - public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); - - /// - /// Get ElectricResistance in Megaohms. - /// - public double Megaohms => As(ElectricResistanceUnit.Megaohm); - - /// - /// Get ElectricResistance in Milliohms. - /// - public double Milliohms => As(ElectricResistanceUnit.Milliohm); - - /// - /// Get ElectricResistance in Ohms. - /// - public double Ohms => As(ElectricResistanceUnit.Ohm); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. - /// - public static ElectricResistance Zero => new ElectricResistance(0, BaseUnit); - - /// - /// Get ElectricResistance from Kiloohms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromKiloohms(double kiloohms) -#else - public static ElectricResistance FromKiloohms(QuantityValue kiloohms) -#endif - { - double value = (double) kiloohms; - return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); - } - - /// - /// Get ElectricResistance from Megaohms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMegaohms(double megaohms) -#else - public static ElectricResistance FromMegaohms(QuantityValue megaohms) -#endif - { - double value = (double) megaohms; - return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); - } - - /// - /// Get ElectricResistance from Milliohms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMilliohms(double milliohms) -#else - public static ElectricResistance FromMilliohms(QuantityValue milliohms) -#endif - { - double value = (double) milliohms; - return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); - } - - /// - /// Get ElectricResistance from Ohms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromOhms(double ohms) -#else - public static ElectricResistance FromOhms(QuantityValue ohms) -#endif - { - double value = (double) ohms; - return new ElectricResistance(value, ElectricResistanceUnit.Ohm); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricResistance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricResistance From(double value, ElectricResistanceUnit fromUnit) -#else - public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) -#endif - { - return new ElectricResistance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricResistanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricResistance)) throw new ArgumentException("Expected type ElectricResistance.", nameof(obj)); - - return CompareTo((ElectricResistance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricResistance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricResistance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricResistance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricResistance to another ElectricResistance with the unit representation . - /// - /// A ElectricResistance with the specified unit. - public ElectricResistance ToUnit(ElectricResistanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricResistance(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d; - case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d; - case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d; - case ElectricResistanceUnit.Ohm: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricResistanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d; - case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d; - case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d; - case ElectricResistanceUnit.Ohm: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricResistance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricResistance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricResistance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistance result) - { - result = default(ElectricResistance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricResistanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricResistanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricResistanceUnit unit) - { - unit = ElectricResistanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricResistanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricResistanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricResistance - /// - public static ElectricResistance MaxValue => new ElectricResistance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricResistance - /// - public static ElectricResistance MinValue => new ElectricResistance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricResistance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs deleted file mode 100644 index bc1a12ad0c..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricResistivity : IQuantity -#else - public partial struct ElectricResistivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricResistivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricResistivity() - { - BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricResistivity(double numericValue, ElectricResistivityUnit unit) - { - if(unit == ElectricResistivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricResistivity; - - /// - /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. - /// - public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricResistivity quantity. - /// - public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricResistivity in MicroohmMeters. - /// - public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); - - /// - /// Get ElectricResistivity in MilliohmMeters. - /// - public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); - - /// - /// Get ElectricResistivity in NanoohmMeters. - /// - public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); - - /// - /// Get ElectricResistivity in OhmMeters. - /// - public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. - /// - public static ElectricResistivity Zero => new ElectricResistivity(0, BaseUnit); - - /// - /// Get ElectricResistivity from MicroohmMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMicroohmMeters(double microohmmeters) -#else - public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) -#endif - { - double value = (double) microohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); - } - - /// - /// Get ElectricResistivity from MilliohmMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMilliohmMeters(double milliohmmeters) -#else - public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) -#endif - { - double value = (double) milliohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); - } - - /// - /// Get ElectricResistivity from NanoohmMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromNanoohmMeters(double nanoohmmeters) -#else - public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) -#endif - { - double value = (double) nanoohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); - } - - /// - /// Get ElectricResistivity from OhmMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromOhmMeters(double ohmmeters) -#else - public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) -#endif - { - double value = (double) ohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricResistivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricResistivity From(double value, ElectricResistivityUnit fromUnit) -#else - public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) -#endif - { - return new ElectricResistivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricResistivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricResistivity)) throw new ArgumentException("Expected type ElectricResistivity.", nameof(obj)); - - return CompareTo((ElectricResistivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricResistivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricResistivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricResistivity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistivity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . - /// - /// A ElectricResistivity with the specified unit. - public ElectricResistivity ToUnit(ElectricResistivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricResistivity(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 AsBaseUnit() - { - switch(Unit) - { - case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; - case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; - case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; - case ElectricResistivityUnit.OhmMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricResistivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; - case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; - case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; - case ElectricResistivityUnit.OhmMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ElectricResistivity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricResistivity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistivityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ElectricResistivity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistivity result) - { - result = default(ElectricResistivity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ElectricResistivityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ElectricResistivityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ElectricResistivityUnit unit) - { - unit = ElectricResistivityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ElectricResistivityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricResistivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricResistivity - /// - public static ElectricResistivity MaxValue => new ElectricResistivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricResistivity - /// - public static ElectricResistivity MinValue => new ElectricResistivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricResistivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Energy.Common.g.cs b/Common/GeneratedCode/Quantities/Energy.Common.g.cs deleted file mode 100644 index 679d4ecf0e..0000000000 --- a/Common/GeneratedCode/Quantities/Energy.Common.g.cs +++ /dev/null @@ -1,999 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Energy : IQuantity -#else - public partial struct Energy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly EnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Energy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Energy(double numericValue, EnergyUnit unit) - { - if(unit == EnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Energy; - - /// - /// The base unit of Energy, which is Joule. All conversions go via this value. - /// - public static EnergyUnit BaseUnit => EnergyUnit.Joule; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Energy quantity. - /// - public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); - - /// - /// Get Energy in BritishThermalUnits. - /// - public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); - - /// - /// Get Energy in Calories. - /// - public double Calories => As(EnergyUnit.Calorie); - - /// - /// Get Energy in DecathermsEc. - /// - public double DecathermsEc => As(EnergyUnit.DecathermEc); - - /// - /// Get Energy in DecathermsImperial. - /// - public double DecathermsImperial => As(EnergyUnit.DecathermImperial); - - /// - /// Get Energy in DecathermsUs. - /// - public double DecathermsUs => As(EnergyUnit.DecathermUs); - - /// - /// Get Energy in ElectronVolts. - /// - public double ElectronVolts => As(EnergyUnit.ElectronVolt); - - /// - /// Get Energy in Ergs. - /// - public double Ergs => As(EnergyUnit.Erg); - - /// - /// Get Energy in FootPounds. - /// - public double FootPounds => As(EnergyUnit.FootPound); - - /// - /// Get Energy in GigabritishThermalUnits. - /// - public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); - - /// - /// Get Energy in GigawattHours. - /// - public double GigawattHours => As(EnergyUnit.GigawattHour); - - /// - /// Get Energy in Joules. - /// - public double Joules => As(EnergyUnit.Joule); - - /// - /// Get Energy in KilobritishThermalUnits. - /// - public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); - - /// - /// Get Energy in Kilocalories. - /// - public double Kilocalories => As(EnergyUnit.Kilocalorie); - - /// - /// Get Energy in Kilojoules. - /// - public double Kilojoules => As(EnergyUnit.Kilojoule); - - /// - /// Get Energy in KilowattHours. - /// - public double KilowattHours => As(EnergyUnit.KilowattHour); - - /// - /// Get Energy in MegabritishThermalUnits. - /// - public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); - - /// - /// Get Energy in Megajoules. - /// - public double Megajoules => As(EnergyUnit.Megajoule); - - /// - /// Get Energy in MegawattHours. - /// - public double MegawattHours => As(EnergyUnit.MegawattHour); - - /// - /// Get Energy in ThermsEc. - /// - public double ThermsEc => As(EnergyUnit.ThermEc); - - /// - /// Get Energy in ThermsImperial. - /// - public double ThermsImperial => As(EnergyUnit.ThermImperial); - - /// - /// Get Energy in ThermsUs. - /// - public double ThermsUs => As(EnergyUnit.ThermUs); - - /// - /// Get Energy in WattHours. - /// - public double WattHours => As(EnergyUnit.WattHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Joule. - /// - public static Energy Zero => new Energy(0, BaseUnit); - - /// - /// Get Energy from BritishThermalUnits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromBritishThermalUnits(double britishthermalunits) -#else - public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) -#endif - { - double value = (double) britishthermalunits; - return new Energy(value, EnergyUnit.BritishThermalUnit); - } - - /// - /// Get Energy from Calories. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromCalories(double calories) -#else - public static Energy FromCalories(QuantityValue calories) -#endif - { - double value = (double) calories; - return new Energy(value, EnergyUnit.Calorie); - } - - /// - /// Get Energy from DecathermsEc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsEc(double decathermsec) -#else - public static Energy FromDecathermsEc(QuantityValue decathermsec) -#endif - { - double value = (double) decathermsec; - return new Energy(value, EnergyUnit.DecathermEc); - } - - /// - /// Get Energy from DecathermsImperial. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsImperial(double decathermsimperial) -#else - public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) -#endif - { - double value = (double) decathermsimperial; - return new Energy(value, EnergyUnit.DecathermImperial); - } - - /// - /// Get Energy from DecathermsUs. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsUs(double decathermsus) -#else - public static Energy FromDecathermsUs(QuantityValue decathermsus) -#endif - { - double value = (double) decathermsus; - return new Energy(value, EnergyUnit.DecathermUs); - } - - /// - /// Get Energy from ElectronVolts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromElectronVolts(double electronvolts) -#else - public static Energy FromElectronVolts(QuantityValue electronvolts) -#endif - { - double value = (double) electronvolts; - return new Energy(value, EnergyUnit.ElectronVolt); - } - - /// - /// Get Energy from Ergs. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromErgs(double ergs) -#else - public static Energy FromErgs(QuantityValue ergs) -#endif - { - double value = (double) ergs; - return new Energy(value, EnergyUnit.Erg); - } - - /// - /// Get Energy from FootPounds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromFootPounds(double footpounds) -#else - public static Energy FromFootPounds(QuantityValue footpounds) -#endif - { - double value = (double) footpounds; - return new Energy(value, EnergyUnit.FootPound); - } - - /// - /// Get Energy from GigabritishThermalUnits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigabritishThermalUnits(double gigabritishthermalunits) -#else - public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) -#endif - { - double value = (double) gigabritishthermalunits; - return new Energy(value, EnergyUnit.GigabritishThermalUnit); - } - - /// - /// Get Energy from GigawattHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigawattHours(double gigawatthours) -#else - public static Energy FromGigawattHours(QuantityValue gigawatthours) -#endif - { - double value = (double) gigawatthours; - return new Energy(value, EnergyUnit.GigawattHour); - } - - /// - /// Get Energy from Joules. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromJoules(double joules) -#else - public static Energy FromJoules(QuantityValue joules) -#endif - { - double value = (double) joules; - return new Energy(value, EnergyUnit.Joule); - } - - /// - /// Get Energy from KilobritishThermalUnits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilobritishThermalUnits(double kilobritishthermalunits) -#else - public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) -#endif - { - double value = (double) kilobritishthermalunits; - return new Energy(value, EnergyUnit.KilobritishThermalUnit); - } - - /// - /// Get Energy from Kilocalories. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilocalories(double kilocalories) -#else - public static Energy FromKilocalories(QuantityValue kilocalories) -#endif - { - double value = (double) kilocalories; - return new Energy(value, EnergyUnit.Kilocalorie); - } - - /// - /// Get Energy from Kilojoules. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilojoules(double kilojoules) -#else - public static Energy FromKilojoules(QuantityValue kilojoules) -#endif - { - double value = (double) kilojoules; - return new Energy(value, EnergyUnit.Kilojoule); - } - - /// - /// Get Energy from KilowattHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilowattHours(double kilowatthours) -#else - public static Energy FromKilowattHours(QuantityValue kilowatthours) -#endif - { - double value = (double) kilowatthours; - return new Energy(value, EnergyUnit.KilowattHour); - } - - /// - /// Get Energy from MegabritishThermalUnits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegabritishThermalUnits(double megabritishthermalunits) -#else - public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) -#endif - { - double value = (double) megabritishthermalunits; - return new Energy(value, EnergyUnit.MegabritishThermalUnit); - } - - /// - /// Get Energy from Megajoules. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegajoules(double megajoules) -#else - public static Energy FromMegajoules(QuantityValue megajoules) -#endif - { - double value = (double) megajoules; - return new Energy(value, EnergyUnit.Megajoule); - } - - /// - /// Get Energy from MegawattHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegawattHours(double megawatthours) -#else - public static Energy FromMegawattHours(QuantityValue megawatthours) -#endif - { - double value = (double) megawatthours; - return new Energy(value, EnergyUnit.MegawattHour); - } - - /// - /// Get Energy from ThermsEc. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsEc(double thermsec) -#else - public static Energy FromThermsEc(QuantityValue thermsec) -#endif - { - double value = (double) thermsec; - return new Energy(value, EnergyUnit.ThermEc); - } - - /// - /// Get Energy from ThermsImperial. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsImperial(double thermsimperial) -#else - public static Energy FromThermsImperial(QuantityValue thermsimperial) -#endif - { - double value = (double) thermsimperial; - return new Energy(value, EnergyUnit.ThermImperial); - } - - /// - /// Get Energy from ThermsUs. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsUs(double thermsus) -#else - public static Energy FromThermsUs(QuantityValue thermsus) -#endif - { - double value = (double) thermsus; - return new Energy(value, EnergyUnit.ThermUs); - } - - /// - /// Get Energy from WattHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromWattHours(double watthours) -#else - public static Energy FromWattHours(QuantityValue watthours) -#endif - { - double value = (double) watthours; - return new Energy(value, EnergyUnit.WattHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Energy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Energy From(double value, EnergyUnit fromUnit) -#else - public static Energy From(QuantityValue value, EnergyUnit fromUnit) -#endif - { - return new Energy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(EnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Energy)) throw new ArgumentException("Expected type Energy.", nameof(obj)); - - return CompareTo((Energy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Energy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Energy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Energy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Energy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Energy to another Energy with the unit representation . - /// - /// A Energy with the specified unit. - public Energy ToUnit(EnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Energy(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 AsBaseUnit() - { - switch(Unit) - { - case EnergyUnit.BritishThermalUnit: return _value*1055.05585262; - case EnergyUnit.Calorie: return _value*4.184; - case EnergyUnit.DecathermEc: return (_value*1.05505585262e8) * 1e1d; - case EnergyUnit.DecathermImperial: return (_value*1.05505585257348e8) * 1e1d; - case EnergyUnit.DecathermUs: return (_value*1.054804e8) * 1e1d; - case EnergyUnit.ElectronVolt: return _value*1.602176565e-19; - case EnergyUnit.Erg: return _value*1e-7; - case EnergyUnit.FootPound: return _value*1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (_value*1055.05585262) * 1e9d; - case EnergyUnit.GigawattHour: return (_value*3600d) * 1e9d; - case EnergyUnit.Joule: return _value; - case EnergyUnit.KilobritishThermalUnit: return (_value*1055.05585262) * 1e3d; - case EnergyUnit.Kilocalorie: return (_value*4.184) * 1e3d; - case EnergyUnit.Kilojoule: return (_value) * 1e3d; - case EnergyUnit.KilowattHour: return (_value*3600d) * 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (_value*1055.05585262) * 1e6d; - case EnergyUnit.Megajoule: return (_value) * 1e6d; - case EnergyUnit.MegawattHour: return (_value*3600d) * 1e6d; - case EnergyUnit.ThermEc: return _value*1.05505585262e8; - case EnergyUnit.ThermImperial: return _value*1.05505585257348e8; - case EnergyUnit.ThermUs: return _value*1.054804e8; - case EnergyUnit.WattHour: return _value*3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(EnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case EnergyUnit.BritishThermalUnit: return baseUnitValue/1055.05585262; - case EnergyUnit.Calorie: return baseUnitValue/4.184; - case EnergyUnit.DecathermEc: return (baseUnitValue/1.05505585262e8) / 1e1d; - case EnergyUnit.DecathermImperial: return (baseUnitValue/1.05505585257348e8) / 1e1d; - case EnergyUnit.DecathermUs: return (baseUnitValue/1.054804e8) / 1e1d; - case EnergyUnit.ElectronVolt: return baseUnitValue/1.602176565e-19; - case EnergyUnit.Erg: return baseUnitValue/1e-7; - case EnergyUnit.FootPound: return baseUnitValue/1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e9d; - case EnergyUnit.GigawattHour: return (baseUnitValue/3600d) / 1e9d; - case EnergyUnit.Joule: return baseUnitValue; - case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e3d; - case EnergyUnit.Kilocalorie: return (baseUnitValue/4.184) / 1e3d; - case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; - case EnergyUnit.KilowattHour: return (baseUnitValue/3600d) / 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e6d; - case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; - case EnergyUnit.MegawattHour: return (baseUnitValue/3600d) / 1e6d; - case EnergyUnit.ThermEc: return baseUnitValue/1.05505585262e8; - case EnergyUnit.ThermImperial: return baseUnitValue/1.05505585257348e8; - case EnergyUnit.ThermUs: return baseUnitValue/1.054804e8; - case EnergyUnit.WattHour: return baseUnitValue/3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Energy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Energy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EnergyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out EnergyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Energy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Energy result) - { - result = default(Energy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static EnergyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == EnergyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out EnergyUnit unit) - { - unit = EnergyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == EnergyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(EnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Energy - /// - public static Energy MaxValue => new Energy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Energy - /// - public static Energy MinValue => new Energy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Energy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Energy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Entropy.Common.g.cs b/Common/GeneratedCode/Quantities/Entropy.Common.g.cs deleted file mode 100644 index d2b8047b4a..0000000000 --- a/Common/GeneratedCode/Quantities/Entropy.Common.g.cs +++ /dev/null @@ -1,669 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Entropy : IQuantity -#else - public partial struct Entropy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly EntropyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Entropy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Entropy(double numericValue, EntropyUnit unit) - { - if(unit == EntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Entropy; - - /// - /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. - /// - public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Entropy quantity. - /// - public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); - - /// - /// Get Entropy in CaloriesPerKelvin. - /// - public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); - - /// - /// Get Entropy in JoulesPerDegreeCelsius. - /// - public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); - - /// - /// Get Entropy in JoulesPerKelvin. - /// - public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); - - /// - /// Get Entropy in KilocaloriesPerKelvin. - /// - public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); - - /// - /// Get Entropy in KilojoulesPerDegreeCelsius. - /// - public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); - - /// - /// Get Entropy in KilojoulesPerKelvin. - /// - public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); - - /// - /// Get Entropy in MegajoulesPerKelvin. - /// - public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. - /// - public static Entropy Zero => new Entropy(0, BaseUnit); - - /// - /// Get Entropy from CaloriesPerKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromCaloriesPerKelvin(double caloriesperkelvin) -#else - public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) -#endif - { - double value = (double) caloriesperkelvin; - return new Entropy(value, EntropyUnit.CaloriePerKelvin); - } - - /// - /// Get Entropy from JoulesPerDegreeCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromJoulesPerDegreeCelsius(double joulesperdegreecelsius) -#else - public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) -#endif - { - double value = (double) joulesperdegreecelsius; - return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); - } - - /// - /// Get Entropy from JoulesPerKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromJoulesPerKelvin(double joulesperkelvin) -#else - public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) -#endif - { - double value = (double) joulesperkelvin; - return new Entropy(value, EntropyUnit.JoulePerKelvin); - } - - /// - /// Get Entropy from KilocaloriesPerKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilocaloriesPerKelvin(double kilocaloriesperkelvin) -#else - public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) -#endif - { - double value = (double) kilocaloriesperkelvin; - return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); - } - - /// - /// Get Entropy from KilojoulesPerDegreeCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilojoulesPerDegreeCelsius(double kilojoulesperdegreecelsius) -#else - public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) -#endif - { - double value = (double) kilojoulesperdegreecelsius; - return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); - } - - /// - /// Get Entropy from KilojoulesPerKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilojoulesPerKelvin(double kilojoulesperkelvin) -#else - public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) -#endif - { - double value = (double) kilojoulesperkelvin; - return new Entropy(value, EntropyUnit.KilojoulePerKelvin); - } - - /// - /// Get Entropy from MegajoulesPerKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromMegajoulesPerKelvin(double megajoulesperkelvin) -#else - public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) -#endif - { - double value = (double) megajoulesperkelvin; - return new Entropy(value, EntropyUnit.MegajoulePerKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Entropy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Entropy From(double value, EntropyUnit fromUnit) -#else - public static Entropy From(QuantityValue value, EntropyUnit fromUnit) -#endif - { - return new Entropy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(EntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Entropy)) throw new ArgumentException("Expected type Entropy.", nameof(obj)); - - return CompareTo((Entropy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Entropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Entropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Entropy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Entropy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EntropyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Entropy to another Entropy with the unit representation . - /// - /// A Entropy with the specified unit. - public Entropy ToUnit(EntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Entropy(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 AsBaseUnit() - { - switch(Unit) - { - case EntropyUnit.CaloriePerKelvin: return _value*4.184; - case EntropyUnit.JoulePerDegreeCelsius: return _value; - case EntropyUnit.JoulePerKelvin: return _value; - case EntropyUnit.KilocaloriePerKelvin: return (_value*4.184) * 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (_value) * 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (_value) * 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(EntropyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case EntropyUnit.CaloriePerKelvin: return baseUnitValue/4.184; - case EntropyUnit.JoulePerDegreeCelsius: return baseUnitValue; - case EntropyUnit.JoulePerKelvin: return baseUnitValue; - case EntropyUnit.KilocaloriePerKelvin: return (baseUnitValue/4.184) / 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (baseUnitValue) / 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (baseUnitValue) / 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Entropy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Entropy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EntropyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out EntropyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Entropy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Entropy result) - { - result = default(Entropy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static EntropyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == EntropyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out EntropyUnit unit) - { - unit = EntropyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == EntropyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(EntropyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Entropy - /// - public static Entropy MaxValue => new Entropy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Entropy - /// - public static Entropy MinValue => new Entropy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Entropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Entropy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Force.Common.g.cs b/Common/GeneratedCode/Quantities/Force.Common.g.cs deleted file mode 100644 index 527bd45208..0000000000 --- a/Common/GeneratedCode/Quantities/Force.Common.g.cs +++ /dev/null @@ -1,735 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Force : IQuantity -#else - public partial struct Force : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Force() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Force(double numericValue, ForceUnit unit) - { - if(unit == ForceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Force; - - /// - /// The base unit of Force, which is Newton. All conversions go via this value. - /// - public static ForceUnit BaseUnit => ForceUnit.Newton; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Force quantity. - /// - public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); - - /// - /// Get Force in Decanewtons. - /// - public double Decanewtons => As(ForceUnit.Decanewton); - - /// - /// Get Force in Dyne. - /// - public double Dyne => As(ForceUnit.Dyn); - - /// - /// Get Force in KilogramsForce. - /// - public double KilogramsForce => As(ForceUnit.KilogramForce); - - /// - /// Get Force in Kilonewtons. - /// - public double Kilonewtons => As(ForceUnit.Kilonewton); - - /// - /// Get Force in KiloPonds. - /// - public double KiloPonds => As(ForceUnit.KiloPond); - - /// - /// Get Force in Meganewtons. - /// - public double Meganewtons => As(ForceUnit.Meganewton); - - /// - /// Get Force in Newtons. - /// - public double Newtons => As(ForceUnit.Newton); - - /// - /// Get Force in Poundals. - /// - public double Poundals => As(ForceUnit.Poundal); - - /// - /// Get Force in PoundsForce. - /// - public double PoundsForce => As(ForceUnit.PoundForce); - - /// - /// Get Force in TonnesForce. - /// - public double TonnesForce => As(ForceUnit.TonneForce); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Newton. - /// - public static Force Zero => new Force(0, BaseUnit); - - /// - /// Get Force from Decanewtons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromDecanewtons(double decanewtons) -#else - public static Force FromDecanewtons(QuantityValue decanewtons) -#endif - { - double value = (double) decanewtons; - return new Force(value, ForceUnit.Decanewton); - } - - /// - /// Get Force from Dyne. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromDyne(double dyne) -#else - public static Force FromDyne(QuantityValue dyne) -#endif - { - double value = (double) dyne; - return new Force(value, ForceUnit.Dyn); - } - - /// - /// Get Force from KilogramsForce. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilogramsForce(double kilogramsforce) -#else - public static Force FromKilogramsForce(QuantityValue kilogramsforce) -#endif - { - double value = (double) kilogramsforce; - return new Force(value, ForceUnit.KilogramForce); - } - - /// - /// Get Force from Kilonewtons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilonewtons(double kilonewtons) -#else - public static Force FromKilonewtons(QuantityValue kilonewtons) -#endif - { - double value = (double) kilonewtons; - return new Force(value, ForceUnit.Kilonewton); - } - - /// - /// Get Force from KiloPonds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKiloPonds(double kiloponds) -#else - public static Force FromKiloPonds(QuantityValue kiloponds) -#endif - { - double value = (double) kiloponds; - return new Force(value, ForceUnit.KiloPond); - } - - /// - /// Get Force from Meganewtons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMeganewtons(double meganewtons) -#else - public static Force FromMeganewtons(QuantityValue meganewtons) -#endif - { - double value = (double) meganewtons; - return new Force(value, ForceUnit.Meganewton); - } - - /// - /// Get Force from Newtons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromNewtons(double newtons) -#else - public static Force FromNewtons(QuantityValue newtons) -#endif - { - double value = (double) newtons; - return new Force(value, ForceUnit.Newton); - } - - /// - /// Get Force from Poundals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromPoundals(double poundals) -#else - public static Force FromPoundals(QuantityValue poundals) -#endif - { - double value = (double) poundals; - return new Force(value, ForceUnit.Poundal); - } - - /// - /// Get Force from PoundsForce. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromPoundsForce(double poundsforce) -#else - public static Force FromPoundsForce(QuantityValue poundsforce) -#endif - { - double value = (double) poundsforce; - return new Force(value, ForceUnit.PoundForce); - } - - /// - /// Get Force from TonnesForce. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromTonnesForce(double tonnesforce) -#else - public static Force FromTonnesForce(QuantityValue tonnesforce) -#endif - { - double value = (double) tonnesforce; - return new Force(value, ForceUnit.TonneForce); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Force unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Force From(double value, ForceUnit fromUnit) -#else - public static Force From(QuantityValue value, ForceUnit fromUnit) -#endif - { - return new Force((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Force)) throw new ArgumentException("Expected type Force.", nameof(obj)); - - return CompareTo((Force)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Force other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Force within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Force other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Force. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Force to another Force with the unit representation . - /// - /// A Force with the specified unit. - public Force ToUnit(ForceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Force(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 AsBaseUnit() - { - switch(Unit) - { - case ForceUnit.Decanewton: return (_value) * 1e1d; - case ForceUnit.Dyn: return _value/1e5; - case ForceUnit.KilogramForce: return _value*9.80665002864; - case ForceUnit.Kilonewton: return (_value) * 1e3d; - case ForceUnit.KiloPond: return _value*9.80665002864; - case ForceUnit.Meganewton: return (_value) * 1e6d; - case ForceUnit.Newton: return _value; - case ForceUnit.Poundal: return _value*0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return _value*4.4482216152605095551842641431421; - case ForceUnit.TonneForce: return _value*9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; - case ForceUnit.Dyn: return baseUnitValue*1e5; - case ForceUnit.KilogramForce: return baseUnitValue/9.80665002864; - case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; - case ForceUnit.KiloPond: return baseUnitValue/9.80665002864; - case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; - case ForceUnit.Newton: return baseUnitValue; - case ForceUnit.Poundal: return baseUnitValue/0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return baseUnitValue/4.4482216152605095551842641431421; - case ForceUnit.TonneForce: return baseUnitValue/9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Force Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Force result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ForceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Force ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Force result) - { - result = default(Force); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ForceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ForceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ForceUnit unit) - { - unit = ForceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ForceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ForceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Force - /// - public static Force MaxValue => new Force(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Force - /// - public static Force MinValue => new Force(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Force.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Force.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs b/Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs deleted file mode 100644 index 9c1f7f2341..0000000000 --- a/Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs +++ /dev/null @@ -1,757 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ForceChangeRate : IQuantity -#else - public partial struct ForceChangeRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForceChangeRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ForceChangeRate() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ForceChangeRate(double numericValue, ForceChangeRateUnit unit) - { - if(unit == ForceChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ForceChangeRate; - - /// - /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. - /// - public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ForceChangeRate quantity. - /// - public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); - - /// - /// Get ForceChangeRate in CentinewtonsPerSecond. - /// - public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); - - /// - /// Get ForceChangeRate in DecanewtonsPerMinute. - /// - public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); - - /// - /// Get ForceChangeRate in DecanewtonsPerSecond. - /// - public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); - - /// - /// Get ForceChangeRate in DecinewtonsPerSecond. - /// - public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); - - /// - /// Get ForceChangeRate in KilonewtonsPerMinute. - /// - public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); - - /// - /// Get ForceChangeRate in KilonewtonsPerSecond. - /// - public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); - - /// - /// Get ForceChangeRate in MicronewtonsPerSecond. - /// - public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); - - /// - /// Get ForceChangeRate in MillinewtonsPerSecond. - /// - public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); - - /// - /// Get ForceChangeRate in NanonewtonsPerSecond. - /// - public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); - - /// - /// Get ForceChangeRate in NewtonsPerMinute. - /// - public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); - - /// - /// Get ForceChangeRate in NewtonsPerSecond. - /// - public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. - /// - public static ForceChangeRate Zero => new ForceChangeRate(0, BaseUnit); - - /// - /// Get ForceChangeRate from CentinewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromCentinewtonsPerSecond(double centinewtonspersecond) -#else - public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) -#endif - { - double value = (double) centinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); - } - - /// - /// Get ForceChangeRate from DecanewtonsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecanewtonsPerMinute(double decanewtonsperminute) -#else - public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) -#endif - { - double value = (double) decanewtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); - } - - /// - /// Get ForceChangeRate from DecanewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecanewtonsPerSecond(double decanewtonspersecond) -#else - public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) -#endif - { - double value = (double) decanewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); - } - - /// - /// Get ForceChangeRate from DecinewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecinewtonsPerSecond(double decinewtonspersecond) -#else - public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) -#endif - { - double value = (double) decinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); - } - - /// - /// Get ForceChangeRate from KilonewtonsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilonewtonsPerMinute(double kilonewtonsperminute) -#else - public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) -#endif - { - double value = (double) kilonewtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); - } - - /// - /// Get ForceChangeRate from KilonewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilonewtonsPerSecond(double kilonewtonspersecond) -#else - public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) -#endif - { - double value = (double) kilonewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); - } - - /// - /// Get ForceChangeRate from MicronewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromMicronewtonsPerSecond(double micronewtonspersecond) -#else - public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) -#endif - { - double value = (double) micronewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); - } - - /// - /// Get ForceChangeRate from MillinewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromMillinewtonsPerSecond(double millinewtonspersecond) -#else - public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) -#endif - { - double value = (double) millinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); - } - - /// - /// Get ForceChangeRate from NanonewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNanonewtonsPerSecond(double nanonewtonspersecond) -#else - public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) -#endif - { - double value = (double) nanonewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); - } - - /// - /// Get ForceChangeRate from NewtonsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNewtonsPerMinute(double newtonsperminute) -#else - public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) -#endif - { - double value = (double) newtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); - } - - /// - /// Get ForceChangeRate from NewtonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNewtonsPerSecond(double newtonspersecond) -#else - public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) -#endif - { - double value = (double) newtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ForceChangeRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) -#else - public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) -#endif - { - return new ForceChangeRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForceChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ForceChangeRate)) throw new ArgumentException("Expected type ForceChangeRate.", nameof(obj)); - - return CompareTo((ForceChangeRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ForceChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ForceChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ForceChangeRate other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForceChangeRate. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceChangeRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . - /// - /// A ForceChangeRate with the specified unit. - public ForceChangeRate ToUnit(ForceChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ForceChangeRate(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 AsBaseUnit() - { - switch(Unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (_value/60) * 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (_value/60) * 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return _value/60; - case ForceChangeRateUnit.NewtonPerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForceChangeRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue*60) / 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue*60) / 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue*60; - case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ForceChangeRate Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceChangeRateUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ForceChangeRate ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ForceChangeRate result) - { - result = default(ForceChangeRate); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ForceChangeRateUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ForceChangeRateUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ForceChangeRateUnit unit) - { - unit = ForceChangeRateUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ForceChangeRateUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ForceChangeRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ForceChangeRate - /// - public static ForceChangeRate MaxValue => new ForceChangeRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ForceChangeRate - /// - public static ForceChangeRate MinValue => new ForceChangeRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ForceChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs b/Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs deleted file mode 100644 index a4099b4aa0..0000000000 --- a/Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs +++ /dev/null @@ -1,713 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The magnitude of force per unit length. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ForcePerLength : IQuantity -#else - public partial struct ForcePerLength : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForcePerLengthUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ForcePerLength() - { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ForcePerLength(double numericValue, ForcePerLengthUnit unit) - { - if(unit == ForcePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ForcePerLength; - - /// - /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. - /// - public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ForcePerLength quantity. - /// - public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); - - /// - /// Get ForcePerLength in CentinewtonsPerMeter. - /// - public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); - - /// - /// Get ForcePerLength in DecinewtonsPerMeter. - /// - public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); - - /// - /// Get ForcePerLength in KilogramsForcePerMeter. - /// - public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); - - /// - /// Get ForcePerLength in KilonewtonsPerMeter. - /// - public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); - - /// - /// Get ForcePerLength in MeganewtonsPerMeter. - /// - public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); - - /// - /// Get ForcePerLength in MicronewtonsPerMeter. - /// - public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); - - /// - /// Get ForcePerLength in MillinewtonsPerMeter. - /// - public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); - - /// - /// Get ForcePerLength in NanonewtonsPerMeter. - /// - public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); - - /// - /// Get ForcePerLength in NewtonsPerMeter. - /// - public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. - /// - public static ForcePerLength Zero => new ForcePerLength(0, BaseUnit); - - /// - /// Get ForcePerLength from CentinewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromCentinewtonsPerMeter(double centinewtonspermeter) -#else - public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) -#endif - { - double value = (double) centinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); - } - - /// - /// Get ForcePerLength from DecinewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecinewtonsPerMeter(double decinewtonspermeter) -#else - public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) -#endif - { - double value = (double) decinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); - } - - /// - /// Get ForcePerLength from KilogramsForcePerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilogramsForcePerMeter(double kilogramsforcepermeter) -#else - public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) -#endif - { - double value = (double) kilogramsforcepermeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); - } - - /// - /// Get ForcePerLength from KilonewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilonewtonsPerMeter(double kilonewtonspermeter) -#else - public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) -#endif - { - double value = (double) kilonewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); - } - - /// - /// Get ForcePerLength from MeganewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMeganewtonsPerMeter(double meganewtonspermeter) -#else - public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) -#endif - { - double value = (double) meganewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); - } - - /// - /// Get ForcePerLength from MicronewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMicronewtonsPerMeter(double micronewtonspermeter) -#else - public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) -#endif - { - double value = (double) micronewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); - } - - /// - /// Get ForcePerLength from MillinewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMillinewtonsPerMeter(double millinewtonspermeter) -#else - public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) -#endif - { - double value = (double) millinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); - } - - /// - /// Get ForcePerLength from NanonewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNanonewtonsPerMeter(double nanonewtonspermeter) -#else - public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) -#endif - { - double value = (double) nanonewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); - } - - /// - /// Get ForcePerLength from NewtonsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNewtonsPerMeter(double newtonspermeter) -#else - public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) -#endif - { - double value = (double) newtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ForcePerLength unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) -#else - public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) -#endif - { - return new ForcePerLength((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForcePerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ForcePerLength)) throw new ArgumentException("Expected type ForcePerLength.", nameof(obj)); - - return CompareTo((ForcePerLength)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ForcePerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ForcePerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ForcePerLength other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForcePerLength. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForcePerLengthUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ForcePerLength to another ForcePerLength with the unit representation . - /// - /// A ForcePerLength with the specified unit. - public ForcePerLength ToUnit(ForcePerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ForcePerLength(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 AsBaseUnit() - { - switch(Unit) - { - case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; - case ForcePerLengthUnit.KilogramForcePerMeter: return _value*9.80665002864; - case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; - case ForcePerLengthUnit.NewtonPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForcePerLengthUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; - case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue/9.80665002864; - case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; - case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ForcePerLength Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ForcePerLength result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForcePerLengthUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ForcePerLength ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ForcePerLength result) - { - result = default(ForcePerLength); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ForcePerLengthUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ForcePerLengthUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForcePerLengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ForcePerLengthUnit unit) - { - unit = ForcePerLengthUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ForcePerLengthUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ForcePerLengthUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ForcePerLength - /// - public static ForcePerLength MaxValue => new ForcePerLength(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ForcePerLength - /// - public static ForcePerLength MinValue => new ForcePerLength(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ForcePerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Frequency.Common.g.cs b/Common/GeneratedCode/Quantities/Frequency.Common.g.cs deleted file mode 100644 index b9f4b25715..0000000000 --- a/Common/GeneratedCode/Quantities/Frequency.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The number of occurrences of a repeating event per unit time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Frequency : IQuantity -#else - public partial struct Frequency : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly FrequencyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Frequency() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Frequency(double numericValue, FrequencyUnit unit) - { - if(unit == FrequencyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Frequency; - - /// - /// The base unit of Frequency, which is Hertz. All conversions go via this value. - /// - public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Frequency quantity. - /// - public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); - - /// - /// Get Frequency in CyclesPerHour. - /// - public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); - - /// - /// Get Frequency in CyclesPerMinute. - /// - public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); - - /// - /// Get Frequency in Gigahertz. - /// - public double Gigahertz => As(FrequencyUnit.Gigahertz); - - /// - /// Get Frequency in Hertz. - /// - public double Hertz => As(FrequencyUnit.Hertz); - - /// - /// Get Frequency in Kilohertz. - /// - public double Kilohertz => As(FrequencyUnit.Kilohertz); - - /// - /// Get Frequency in Megahertz. - /// - public double Megahertz => As(FrequencyUnit.Megahertz); - - /// - /// Get Frequency in RadiansPerSecond. - /// - public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); - - /// - /// Get Frequency in Terahertz. - /// - public double Terahertz => As(FrequencyUnit.Terahertz); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. - /// - public static Frequency Zero => new Frequency(0, BaseUnit); - - /// - /// Get Frequency from CyclesPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromCyclesPerHour(double cyclesperhour) -#else - public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) -#endif - { - double value = (double) cyclesperhour; - return new Frequency(value, FrequencyUnit.CyclePerHour); - } - - /// - /// Get Frequency from CyclesPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromCyclesPerMinute(double cyclesperminute) -#else - public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) -#endif - { - double value = (double) cyclesperminute; - return new Frequency(value, FrequencyUnit.CyclePerMinute); - } - - /// - /// Get Frequency from Gigahertz. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromGigahertz(double gigahertz) -#else - public static Frequency FromGigahertz(QuantityValue gigahertz) -#endif - { - double value = (double) gigahertz; - return new Frequency(value, FrequencyUnit.Gigahertz); - } - - /// - /// Get Frequency from Hertz. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromHertz(double hertz) -#else - public static Frequency FromHertz(QuantityValue hertz) -#endif - { - double value = (double) hertz; - return new Frequency(value, FrequencyUnit.Hertz); - } - - /// - /// Get Frequency from Kilohertz. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromKilohertz(double kilohertz) -#else - public static Frequency FromKilohertz(QuantityValue kilohertz) -#endif - { - double value = (double) kilohertz; - return new Frequency(value, FrequencyUnit.Kilohertz); - } - - /// - /// Get Frequency from Megahertz. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromMegahertz(double megahertz) -#else - public static Frequency FromMegahertz(QuantityValue megahertz) -#endif - { - double value = (double) megahertz; - return new Frequency(value, FrequencyUnit.Megahertz); - } - - /// - /// Get Frequency from RadiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromRadiansPerSecond(double radianspersecond) -#else - public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) -#endif - { - double value = (double) radianspersecond; - return new Frequency(value, FrequencyUnit.RadianPerSecond); - } - - /// - /// Get Frequency from Terahertz. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromTerahertz(double terahertz) -#else - public static Frequency FromTerahertz(QuantityValue terahertz) -#endif - { - double value = (double) terahertz; - return new Frequency(value, FrequencyUnit.Terahertz); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Frequency unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Frequency From(double value, FrequencyUnit fromUnit) -#else - public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) -#endif - { - return new Frequency((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(FrequencyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Frequency)) throw new ArgumentException("Expected type Frequency.", nameof(obj)); - - return CompareTo((Frequency)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Frequency other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Frequency within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Frequency other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Frequency. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FrequencyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Frequency to another Frequency with the unit representation . - /// - /// A Frequency with the specified unit. - public Frequency ToUnit(FrequencyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Frequency(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 AsBaseUnit() - { - switch(Unit) - { - case FrequencyUnit.CyclePerHour: return _value/3600; - case FrequencyUnit.CyclePerMinute: return _value/60; - case FrequencyUnit.Gigahertz: return (_value) * 1e9d; - case FrequencyUnit.Hertz: return _value; - case FrequencyUnit.Kilohertz: return (_value) * 1e3d; - case FrequencyUnit.Megahertz: return (_value) * 1e6d; - case FrequencyUnit.RadianPerSecond: return _value/6.2831853072; - case FrequencyUnit.Terahertz: return (_value) * 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(FrequencyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case FrequencyUnit.CyclePerHour: return baseUnitValue*3600; - case FrequencyUnit.CyclePerMinute: return baseUnitValue*60; - case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; - case FrequencyUnit.Hertz: return baseUnitValue; - case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; - case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; - case FrequencyUnit.RadianPerSecond: return baseUnitValue*6.2831853072; - case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Frequency Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Frequency result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FrequencyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out FrequencyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Frequency ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Frequency result) - { - result = default(Frequency); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static FrequencyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == FrequencyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FrequencyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out FrequencyUnit unit) - { - unit = FrequencyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == FrequencyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(FrequencyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Frequency - /// - public static Frequency MaxValue => new Frequency(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Frequency - /// - public static Frequency MinValue => new Frequency(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Frequency.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Frequency.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs b/Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs deleted file mode 100644 index 4c5dc74008..0000000000 --- a/Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs +++ /dev/null @@ -1,867 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Heat flux is the flow of energy per unit of area per unit of time - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class HeatFlux : IQuantity -#else - public partial struct HeatFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly HeatFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static HeatFlux() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - HeatFlux(double numericValue, HeatFluxUnit unit) - { - if(unit == HeatFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.HeatFlux; - - /// - /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. - /// - public static HeatFluxUnit BaseUnit => HeatFluxUnit.WattPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the HeatFlux quantity. - /// - public static HeatFluxUnit[] Units { get; } = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); - - /// - /// Get HeatFlux in BtusPerHourSquareFoot. - /// - public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); - - /// - /// Get HeatFlux in BtusPerMinuteSquareFoot. - /// - public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); - - /// - /// Get HeatFlux in BtusPerSecondSquareFoot. - /// - public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); - - /// - /// Get HeatFlux in BtusPerSecondSquareInch. - /// - public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); - - /// - /// Get HeatFlux in CaloriesPerSecondSquareCentimeter. - /// - public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); - - /// - /// Get HeatFlux in CentiwattsPerSquareMeter. - /// - public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); - - /// - /// Get HeatFlux in DeciwattsPerSquareMeter. - /// - public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); - - /// - /// Get HeatFlux in KilocaloriesPerHourSquareMeter. - /// - public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); - - /// - /// Get HeatFlux in KilocaloriesPerSecondSquareCentimeter. - /// - public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - - /// - /// Get HeatFlux in KilowattsPerSquareMeter. - /// - public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); - - /// - /// Get HeatFlux in MicrowattsPerSquareMeter. - /// - public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); - - /// - /// Get HeatFlux in MilliwattsPerSquareMeter. - /// - public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); - - /// - /// Get HeatFlux in NanowattsPerSquareMeter. - /// - public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); - - /// - /// Get HeatFlux in WattsPerSquareFoot. - /// - public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); - - /// - /// Get HeatFlux in WattsPerSquareInch. - /// - public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); - - /// - /// Get HeatFlux in WattsPerSquareMeter. - /// - public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - public static HeatFlux Zero => new HeatFlux(0, BaseUnit); - - /// - /// Get HeatFlux from BtusPerHourSquareFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerHourSquareFoot(double btusperhoursquarefoot) -#else - public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquarefoot) -#endif - { - double value = (double) btusperhoursquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); - } - - /// - /// Get HeatFlux from BtusPerMinuteSquareFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerMinuteSquareFoot(double btusperminutesquarefoot) -#else - public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesquarefoot) -#endif - { - double value = (double) btusperminutesquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); - } - - /// - /// Get HeatFlux from BtusPerSecondSquareFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerSecondSquareFoot(double btuspersecondsquarefoot) -#else - public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsquarefoot) -#endif - { - double value = (double) btuspersecondsquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); - } - - /// - /// Get HeatFlux from BtusPerSecondSquareInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerSecondSquareInch(double btuspersecondsquareinch) -#else - public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsquareinch) -#endif - { - double value = (double) btuspersecondsquareinch; - return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); - } - - /// - /// Get HeatFlux from CaloriesPerSecondSquareCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double caloriespersecondsquarecentimeter) -#else - public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue caloriespersecondsquarecentimeter) -#endif - { - double value = (double) caloriespersecondsquarecentimeter; - return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); - } - - /// - /// Get HeatFlux from CentiwattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromCentiwattsPerSquareMeter(double centiwattspersquaremeter) -#else - public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspersquaremeter) -#endif - { - double value = (double) centiwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); - } - - /// - /// Get HeatFlux from DeciwattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromDeciwattsPerSquareMeter(double deciwattspersquaremeter) -#else - public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersquaremeter) -#endif - { - double value = (double) deciwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); - } - - /// - /// Get HeatFlux from KilocaloriesPerHourSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilocaloriesPerHourSquareMeter(double kilocaloriesperhoursquaremeter) -#else - public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocaloriesperhoursquaremeter) -#endif - { - double value = (double) kilocaloriesperhoursquaremeter; - return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); - } - - /// - /// Get HeatFlux from KilocaloriesPerSecondSquareCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double kilocaloriespersecondsquarecentimeter) -#else - public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue kilocaloriespersecondsquarecentimeter) -#endif - { - double value = (double) kilocaloriespersecondsquarecentimeter; - return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - } - - /// - /// Get HeatFlux from KilowattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilowattsPerSquareMeter(double kilowattspersquaremeter) -#else - public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) -#endif - { - double value = (double) kilowattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); - } - - /// - /// Get HeatFlux from MicrowattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromMicrowattsPerSquareMeter(double microwattspersquaremeter) -#else - public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) -#endif - { - double value = (double) microwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); - } - - /// - /// Get HeatFlux from MilliwattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) -#else - public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) -#endif - { - double value = (double) milliwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); - } - - /// - /// Get HeatFlux from NanowattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromNanowattsPerSquareMeter(double nanowattspersquaremeter) -#else - public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) -#endif - { - double value = (double) nanowattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); - } - - /// - /// Get HeatFlux from WattsPerSquareFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareFoot(double wattspersquarefoot) -#else - public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) -#endif - { - double value = (double) wattspersquarefoot; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); - } - - /// - /// Get HeatFlux from WattsPerSquareInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareInch(double wattspersquareinch) -#else - public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) -#endif - { - double value = (double) wattspersquareinch; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); - } - - /// - /// Get HeatFlux from WattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareMeter(double wattspersquaremeter) -#else - public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) -#endif - { - double value = (double) wattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// HeatFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static HeatFlux From(double value, HeatFluxUnit fromUnit) -#else - public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) -#endif - { - return new HeatFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(HeatFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is HeatFlux)) throw new ArgumentException("Expected type HeatFlux.", nameof(obj)); - - return CompareTo((HeatFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(HeatFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another HeatFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatFlux. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this HeatFlux to another HeatFlux with the unit representation . - /// - /// A HeatFlux with the specified unit. - public HeatFlux ToUnit(HeatFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new HeatFlux(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 AsBaseUnit() - { - switch(Unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return _value*3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return _value*1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return _value*1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return _value*1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return _value*4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (_value) * 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (_value) * 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return _value*1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (_value*4.1868e4) * 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (_value) * 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (_value) * 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (_value) * 1e-9d; - case HeatFluxUnit.WattPerSquareFoot: return _value*1.07639e1; - case HeatFluxUnit.WattPerSquareInch: return _value*1.5500031e3; - case HeatFluxUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(HeatFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return baseUnitValue/3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return baseUnitValue/1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return baseUnitValue/1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return baseUnitValue/1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return baseUnitValue/4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (baseUnitValue) / 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (baseUnitValue) / 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return baseUnitValue/1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (baseUnitValue/4.1868e4) / 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (baseUnitValue) / 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (baseUnitValue) / 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (baseUnitValue) / 1e-9d; - case HeatFluxUnit.WattPerSquareFoot: return baseUnitValue/1.07639e1; - case HeatFluxUnit.WattPerSquareInch: return baseUnitValue/1.5500031e3; - case HeatFluxUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 HeatFlux Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out HeatFlux result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatFluxUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out HeatFluxUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static HeatFlux ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out HeatFlux result) - { - result = default(HeatFlux); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static HeatFluxUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == HeatFluxUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized HeatFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out HeatFluxUnit unit) - { - unit = HeatFluxUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == HeatFluxUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(HeatFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of HeatFlux - /// - public static HeatFlux MaxValue => new HeatFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of HeatFlux - /// - public static HeatFlux MinValue => new HeatFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => HeatFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => HeatFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs b/Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs deleted file mode 100644 index c3e53a657e..0000000000 --- a/Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs +++ /dev/null @@ -1,559 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class HeatTransferCoefficient : IQuantity -#else - public partial struct HeatTransferCoefficient : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly HeatTransferCoefficientUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static HeatTransferCoefficient() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - HeatTransferCoefficient(double numericValue, HeatTransferCoefficientUnit unit) - { - if(unit == HeatTransferCoefficientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.HeatTransferCoefficient; - - /// - /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. - /// - public static HeatTransferCoefficientUnit BaseUnit => HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the HeatTransferCoefficient quantity. - /// - public static HeatTransferCoefficientUnit[] Units { get; } = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); - - /// - /// Get HeatTransferCoefficient in WattsPerSquareMeterCelsius. - /// - public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - - /// - /// Get HeatTransferCoefficient in WattsPerSquareMeterKelvin. - /// - public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. - /// - public static HeatTransferCoefficient Zero => new HeatTransferCoefficient(0, BaseUnit); - - /// - /// Get HeatTransferCoefficient from WattsPerSquareMeterCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double wattspersquaremetercelsius) -#else - public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue wattspersquaremetercelsius) -#endif - { - double value = (double) wattspersquaremetercelsius; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - } - - /// - /// Get HeatTransferCoefficient from WattsPerSquareMeterKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double wattspersquaremeterkelvin) -#else - public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue wattspersquaremeterkelvin) -#endif - { - double value = (double) wattspersquaremeterkelvin; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// HeatTransferCoefficient unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static HeatTransferCoefficient From(double value, HeatTransferCoefficientUnit fromUnit) -#else - public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) -#endif - { - return new HeatTransferCoefficient((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(HeatTransferCoefficientUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is HeatTransferCoefficient)) throw new ArgumentException("Expected type HeatTransferCoefficient.", nameof(obj)); - - return CompareTo((HeatTransferCoefficient)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(HeatTransferCoefficient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another HeatTransferCoefficient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatTransferCoefficient. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatTransferCoefficientUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . - /// - /// A HeatTransferCoefficient with the specified unit. - public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new HeatTransferCoefficient(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 AsBaseUnit() - { - switch(Unit) - { - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return _value; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(HeatTransferCoefficientUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return baseUnitValue; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 HeatTransferCoefficient Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out HeatTransferCoefficient result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatTransferCoefficientUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static HeatTransferCoefficient ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out HeatTransferCoefficient result) - { - result = default(HeatTransferCoefficient); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static HeatTransferCoefficientUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == HeatTransferCoefficientUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized HeatTransferCoefficientUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out HeatTransferCoefficientUnit unit) - { - unit = HeatTransferCoefficientUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == HeatTransferCoefficientUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(HeatTransferCoefficientUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of HeatTransferCoefficient - /// - public static HeatTransferCoefficient MaxValue => new HeatTransferCoefficient(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of HeatTransferCoefficient - /// - public static HeatTransferCoefficient MinValue => new HeatTransferCoefficient(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => HeatTransferCoefficient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Illuminance.Common.g.cs b/Common/GeneratedCode/Quantities/Illuminance.Common.g.cs deleted file mode 100644 index 461747c421..0000000000 --- a/Common/GeneratedCode/Quantities/Illuminance.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Illuminance : IQuantity -#else - public partial struct Illuminance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IlluminanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Illuminance() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Illuminance(double numericValue, IlluminanceUnit unit) - { - if(unit == IlluminanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Illuminance; - - /// - /// The base unit of Illuminance, which is Lux. All conversions go via this value. - /// - public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Illuminance quantity. - /// - public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); - - /// - /// Get Illuminance in Kilolux. - /// - public double Kilolux => As(IlluminanceUnit.Kilolux); - - /// - /// Get Illuminance in Lux. - /// - public double Lux => As(IlluminanceUnit.Lux); - - /// - /// Get Illuminance in Megalux. - /// - public double Megalux => As(IlluminanceUnit.Megalux); - - /// - /// Get Illuminance in Millilux. - /// - public double Millilux => As(IlluminanceUnit.Millilux); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Lux. - /// - public static Illuminance Zero => new Illuminance(0, BaseUnit); - - /// - /// Get Illuminance from Kilolux. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromKilolux(double kilolux) -#else - public static Illuminance FromKilolux(QuantityValue kilolux) -#endif - { - double value = (double) kilolux; - return new Illuminance(value, IlluminanceUnit.Kilolux); - } - - /// - /// Get Illuminance from Lux. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromLux(double lux) -#else - public static Illuminance FromLux(QuantityValue lux) -#endif - { - double value = (double) lux; - return new Illuminance(value, IlluminanceUnit.Lux); - } - - /// - /// Get Illuminance from Megalux. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromMegalux(double megalux) -#else - public static Illuminance FromMegalux(QuantityValue megalux) -#endif - { - double value = (double) megalux; - return new Illuminance(value, IlluminanceUnit.Megalux); - } - - /// - /// Get Illuminance from Millilux. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromMillilux(double millilux) -#else - public static Illuminance FromMillilux(QuantityValue millilux) -#endif - { - double value = (double) millilux; - return new Illuminance(value, IlluminanceUnit.Millilux); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Illuminance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Illuminance From(double value, IlluminanceUnit fromUnit) -#else - public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) -#endif - { - return new Illuminance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IlluminanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Illuminance)) throw new ArgumentException("Expected type Illuminance.", nameof(obj)); - - return CompareTo((Illuminance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Illuminance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Illuminance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Illuminance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Illuminance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IlluminanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Illuminance to another Illuminance with the unit representation . - /// - /// A Illuminance with the specified unit. - public Illuminance ToUnit(IlluminanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Illuminance(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 AsBaseUnit() - { - switch(Unit) - { - case IlluminanceUnit.Kilolux: return (_value) * 1e3d; - case IlluminanceUnit.Lux: return _value; - case IlluminanceUnit.Megalux: return (_value) * 1e6d; - case IlluminanceUnit.Millilux: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IlluminanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IlluminanceUnit.Kilolux: return (baseUnitValue) / 1e3d; - case IlluminanceUnit.Lux: return baseUnitValue; - case IlluminanceUnit.Megalux: return (baseUnitValue) / 1e6d; - case IlluminanceUnit.Millilux: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Illuminance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Illuminance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IlluminanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out IlluminanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Illuminance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Illuminance result) - { - result = default(Illuminance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static IlluminanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == IlluminanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IlluminanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out IlluminanceUnit unit) - { - unit = IlluminanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == IlluminanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(IlluminanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Illuminance - /// - public static Illuminance MaxValue => new Illuminance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Illuminance - /// - public static Illuminance MinValue => new Illuminance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Illuminance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Illuminance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Information.Common.g.cs b/Common/GeneratedCode/Quantities/Information.Common.g.cs deleted file mode 100644 index 4dc7772045..0000000000 --- a/Common/GeneratedCode/Quantities/Information.Common.g.cs +++ /dev/null @@ -1,1086 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Information : IQuantity -#else - public partial struct Information : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly InformationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Information() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Information(decimal numericValue, InformationUnit unit) - { - if(unit == InformationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = numericValue; - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Information; - - /// - /// The base unit of Information, which is Bit. All conversions go via this value. - /// - public static InformationUnit BaseUnit => InformationUnit.Bit; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Information quantity. - /// - public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); - - /// - /// Get Information in Bits. - /// - public double Bits => As(InformationUnit.Bit); - - /// - /// Get Information in Bytes. - /// - public double Bytes => As(InformationUnit.Byte); - - /// - /// Get Information in Exabits. - /// - public double Exabits => As(InformationUnit.Exabit); - - /// - /// Get Information in Exabytes. - /// - public double Exabytes => As(InformationUnit.Exabyte); - - /// - /// Get Information in Exbibits. - /// - public double Exbibits => As(InformationUnit.Exbibit); - - /// - /// Get Information in Exbibytes. - /// - public double Exbibytes => As(InformationUnit.Exbibyte); - - /// - /// Get Information in Gibibits. - /// - public double Gibibits => As(InformationUnit.Gibibit); - - /// - /// Get Information in Gibibytes. - /// - public double Gibibytes => As(InformationUnit.Gibibyte); - - /// - /// Get Information in Gigabits. - /// - public double Gigabits => As(InformationUnit.Gigabit); - - /// - /// Get Information in Gigabytes. - /// - public double Gigabytes => As(InformationUnit.Gigabyte); - - /// - /// Get Information in Kibibits. - /// - public double Kibibits => As(InformationUnit.Kibibit); - - /// - /// Get Information in Kibibytes. - /// - public double Kibibytes => As(InformationUnit.Kibibyte); - - /// - /// Get Information in Kilobits. - /// - public double Kilobits => As(InformationUnit.Kilobit); - - /// - /// Get Information in Kilobytes. - /// - public double Kilobytes => As(InformationUnit.Kilobyte); - - /// - /// Get Information in Mebibits. - /// - public double Mebibits => As(InformationUnit.Mebibit); - - /// - /// Get Information in Mebibytes. - /// - public double Mebibytes => As(InformationUnit.Mebibyte); - - /// - /// Get Information in Megabits. - /// - public double Megabits => As(InformationUnit.Megabit); - - /// - /// Get Information in Megabytes. - /// - public double Megabytes => As(InformationUnit.Megabyte); - - /// - /// Get Information in Pebibits. - /// - public double Pebibits => As(InformationUnit.Pebibit); - - /// - /// Get Information in Pebibytes. - /// - public double Pebibytes => As(InformationUnit.Pebibyte); - - /// - /// Get Information in Petabits. - /// - public double Petabits => As(InformationUnit.Petabit); - - /// - /// Get Information in Petabytes. - /// - public double Petabytes => As(InformationUnit.Petabyte); - - /// - /// Get Information in Tebibits. - /// - public double Tebibits => As(InformationUnit.Tebibit); - - /// - /// Get Information in Tebibytes. - /// - public double Tebibytes => As(InformationUnit.Tebibyte); - - /// - /// Get Information in Terabits. - /// - public double Terabits => As(InformationUnit.Terabit); - - /// - /// Get Information in Terabytes. - /// - public double Terabytes => As(InformationUnit.Terabyte); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Bit. - /// - public static Information Zero => new Information(0, BaseUnit); - - /// - /// Get Information from Bits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromBits(double bits) -#else - public static Information FromBits(QuantityValue bits) -#endif - { - decimal value = (decimal) bits; - return new Information(value, InformationUnit.Bit); - } - - /// - /// Get Information from Bytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromBytes(double bytes) -#else - public static Information FromBytes(QuantityValue bytes) -#endif - { - decimal value = (decimal) bytes; - return new Information(value, InformationUnit.Byte); - } - - /// - /// Get Information from Exabits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExabits(double exabits) -#else - public static Information FromExabits(QuantityValue exabits) -#endif - { - decimal value = (decimal) exabits; - return new Information(value, InformationUnit.Exabit); - } - - /// - /// Get Information from Exabytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExabytes(double exabytes) -#else - public static Information FromExabytes(QuantityValue exabytes) -#endif - { - decimal value = (decimal) exabytes; - return new Information(value, InformationUnit.Exabyte); - } - - /// - /// Get Information from Exbibits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExbibits(double exbibits) -#else - public static Information FromExbibits(QuantityValue exbibits) -#endif - { - decimal value = (decimal) exbibits; - return new Information(value, InformationUnit.Exbibit); - } - - /// - /// Get Information from Exbibytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExbibytes(double exbibytes) -#else - public static Information FromExbibytes(QuantityValue exbibytes) -#endif - { - decimal value = (decimal) exbibytes; - return new Information(value, InformationUnit.Exbibyte); - } - - /// - /// Get Information from Gibibits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGibibits(double gibibits) -#else - public static Information FromGibibits(QuantityValue gibibits) -#endif - { - decimal value = (decimal) gibibits; - return new Information(value, InformationUnit.Gibibit); - } - - /// - /// Get Information from Gibibytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGibibytes(double gibibytes) -#else - public static Information FromGibibytes(QuantityValue gibibytes) -#endif - { - decimal value = (decimal) gibibytes; - return new Information(value, InformationUnit.Gibibyte); - } - - /// - /// Get Information from Gigabits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGigabits(double gigabits) -#else - public static Information FromGigabits(QuantityValue gigabits) -#endif - { - decimal value = (decimal) gigabits; - return new Information(value, InformationUnit.Gigabit); - } - - /// - /// Get Information from Gigabytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGigabytes(double gigabytes) -#else - public static Information FromGigabytes(QuantityValue gigabytes) -#endif - { - decimal value = (decimal) gigabytes; - return new Information(value, InformationUnit.Gigabyte); - } - - /// - /// Get Information from Kibibits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKibibits(double kibibits) -#else - public static Information FromKibibits(QuantityValue kibibits) -#endif - { - decimal value = (decimal) kibibits; - return new Information(value, InformationUnit.Kibibit); - } - - /// - /// Get Information from Kibibytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKibibytes(double kibibytes) -#else - public static Information FromKibibytes(QuantityValue kibibytes) -#endif - { - decimal value = (decimal) kibibytes; - return new Information(value, InformationUnit.Kibibyte); - } - - /// - /// Get Information from Kilobits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKilobits(double kilobits) -#else - public static Information FromKilobits(QuantityValue kilobits) -#endif - { - decimal value = (decimal) kilobits; - return new Information(value, InformationUnit.Kilobit); - } - - /// - /// Get Information from Kilobytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKilobytes(double kilobytes) -#else - public static Information FromKilobytes(QuantityValue kilobytes) -#endif - { - decimal value = (decimal) kilobytes; - return new Information(value, InformationUnit.Kilobyte); - } - - /// - /// Get Information from Mebibits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMebibits(double mebibits) -#else - public static Information FromMebibits(QuantityValue mebibits) -#endif - { - decimal value = (decimal) mebibits; - return new Information(value, InformationUnit.Mebibit); - } - - /// - /// Get Information from Mebibytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMebibytes(double mebibytes) -#else - public static Information FromMebibytes(QuantityValue mebibytes) -#endif - { - decimal value = (decimal) mebibytes; - return new Information(value, InformationUnit.Mebibyte); - } - - /// - /// Get Information from Megabits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMegabits(double megabits) -#else - public static Information FromMegabits(QuantityValue megabits) -#endif - { - decimal value = (decimal) megabits; - return new Information(value, InformationUnit.Megabit); - } - - /// - /// Get Information from Megabytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMegabytes(double megabytes) -#else - public static Information FromMegabytes(QuantityValue megabytes) -#endif - { - decimal value = (decimal) megabytes; - return new Information(value, InformationUnit.Megabyte); - } - - /// - /// Get Information from Pebibits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPebibits(double pebibits) -#else - public static Information FromPebibits(QuantityValue pebibits) -#endif - { - decimal value = (decimal) pebibits; - return new Information(value, InformationUnit.Pebibit); - } - - /// - /// Get Information from Pebibytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPebibytes(double pebibytes) -#else - public static Information FromPebibytes(QuantityValue pebibytes) -#endif - { - decimal value = (decimal) pebibytes; - return new Information(value, InformationUnit.Pebibyte); - } - - /// - /// Get Information from Petabits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPetabits(double petabits) -#else - public static Information FromPetabits(QuantityValue petabits) -#endif - { - decimal value = (decimal) petabits; - return new Information(value, InformationUnit.Petabit); - } - - /// - /// Get Information from Petabytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPetabytes(double petabytes) -#else - public static Information FromPetabytes(QuantityValue petabytes) -#endif - { - decimal value = (decimal) petabytes; - return new Information(value, InformationUnit.Petabyte); - } - - /// - /// Get Information from Tebibits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTebibits(double tebibits) -#else - public static Information FromTebibits(QuantityValue tebibits) -#endif - { - decimal value = (decimal) tebibits; - return new Information(value, InformationUnit.Tebibit); - } - - /// - /// Get Information from Tebibytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTebibytes(double tebibytes) -#else - public static Information FromTebibytes(QuantityValue tebibytes) -#endif - { - decimal value = (decimal) tebibytes; - return new Information(value, InformationUnit.Tebibyte); - } - - /// - /// Get Information from Terabits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTerabits(double terabits) -#else - public static Information FromTerabits(QuantityValue terabits) -#endif - { - decimal value = (decimal) terabits; - return new Information(value, InformationUnit.Terabit); - } - - /// - /// Get Information from Terabytes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTerabytes(double terabytes) -#else - public static Information FromTerabytes(QuantityValue terabytes) -#endif - { - decimal value = (decimal) terabytes; - return new Information(value, InformationUnit.Terabyte); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Information unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Information From(double value, InformationUnit fromUnit) -#else - public static Information From(QuantityValue value, InformationUnit fromUnit) -#endif - { - return new Information((decimal)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(InformationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Information)) throw new ArgumentException("Expected type Information.", nameof(obj)); - - return CompareTo((Information)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Information other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Information within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Information other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Information. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(InformationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Information to another Information with the unit representation . - /// - /// A Information with the specified unit. - public Information ToUnit(InformationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Information(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 decimal AsBaseUnit() - { - switch(Unit) - { - case InformationUnit.Bit: return _value; - case InformationUnit.Byte: return _value*8m; - case InformationUnit.Exabit: return (_value) * 1e18m; - case InformationUnit.Exabyte: return (_value*8m) * 1e18m; - case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (_value*8m) * (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (_value) * 1e9m; - case InformationUnit.Gigabyte: return (_value*8m) * 1e9m; - case InformationUnit.Kibibit: return (_value) * 1024m; - case InformationUnit.Kibibyte: return (_value*8m) * 1024m; - case InformationUnit.Kilobit: return (_value) * 1e3m; - case InformationUnit.Kilobyte: return (_value*8m) * 1e3m; - case InformationUnit.Mebibit: return (_value) * (1024m * 1024); - case InformationUnit.Mebibyte: return (_value*8m) * (1024m * 1024); - case InformationUnit.Megabit: return (_value) * 1e6m; - case InformationUnit.Megabyte: return (_value*8m) * 1e6m; - case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (_value) * 1e15m; - case InformationUnit.Petabyte: return (_value*8m) * 1e15m; - case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (_value) * 1e12m; - case InformationUnit.Terabyte: return (_value*8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(InformationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case InformationUnit.Bit: return baseUnitValue; - case InformationUnit.Byte: return baseUnitValue/8m; - case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; - case InformationUnit.Exabyte: return (baseUnitValue/8m) / 1e18m; - case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; - case InformationUnit.Gigabyte: return (baseUnitValue/8m) / 1e9m; - case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; - case InformationUnit.Kibibyte: return (baseUnitValue/8m) / 1024m; - case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; - case InformationUnit.Kilobyte: return (baseUnitValue/8m) / 1e3m; - case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); - case InformationUnit.Mebibyte: return (baseUnitValue/8m) / (1024m * 1024); - case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; - case InformationUnit.Megabyte: return (baseUnitValue/8m) / 1e6m; - case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; - case InformationUnit.Petabyte: return (baseUnitValue/8m) / 1e15m; - case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; - case InformationUnit.Terabyte: return (baseUnitValue/8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Information Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Information result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static InformationUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out InformationUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Information ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) - { - result = default(Information); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static InformationUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == InformationUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized InformationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out InformationUnit unit) - { - unit = InformationUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == InformationUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(InformationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Information - /// - public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Information - /// - public static Information MinValue => new Information(decimal.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Information.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Information.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Irradiance.Common.g.cs b/Common/GeneratedCode/Quantities/Irradiance.Common.g.cs deleted file mode 100644 index 9cf07001d2..0000000000 --- a/Common/GeneratedCode/Quantities/Irradiance.Common.g.cs +++ /dev/null @@ -1,559 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Irradiance : IQuantity -#else - public partial struct Irradiance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IrradianceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Irradiance() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Irradiance(double numericValue, IrradianceUnit unit) - { - if(unit == IrradianceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Irradiance; - - /// - /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. - /// - public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Irradiance quantity. - /// - public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); - - /// - /// Get Irradiance in KilowattsPerSquareMeter. - /// - public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); - - /// - /// Get Irradiance in WattsPerSquareMeter. - /// - public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - public static Irradiance Zero => new Irradiance(0, BaseUnit); - - /// - /// Get Irradiance from KilowattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) -#else - public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) -#endif - { - double value = (double) kilowattspersquaremeter; - return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); - } - - /// - /// Get Irradiance from WattsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) -#else - public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) -#endif - { - double value = (double) wattspersquaremeter; - return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Irradiance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Irradiance From(double value, IrradianceUnit fromUnit) -#else - public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) -#endif - { - return new Irradiance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IrradianceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Irradiance)) throw new ArgumentException("Expected type Irradiance.", nameof(obj)); - - return CompareTo((Irradiance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Irradiance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Irradiance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Irradiance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradianceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Irradiance to another Irradiance with the unit representation . - /// - /// A Irradiance with the specified unit. - public Irradiance ToUnit(IrradianceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Irradiance(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 AsBaseUnit() - { - switch(Unit) - { - case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case IrradianceUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IrradianceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Irradiance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Irradiance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradianceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out IrradianceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Irradiance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Irradiance result) - { - result = default(Irradiance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static IrradianceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == IrradianceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradianceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out IrradianceUnit unit) - { - unit = IrradianceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == IrradianceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(IrradianceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Irradiance - /// - public static Irradiance MaxValue => new Irradiance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Irradiance - /// - public static Irradiance MinValue => new Irradiance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Irradiance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Irradiance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Irradiation.Common.g.cs b/Common/GeneratedCode/Quantities/Irradiation.Common.g.cs deleted file mode 100644 index f200105b05..0000000000 --- a/Common/GeneratedCode/Quantities/Irradiation.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Irradiation : IQuantity -#else - public partial struct Irradiation : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IrradiationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Irradiation() - { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Irradiation(double numericValue, IrradiationUnit unit) - { - if(unit == IrradiationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Irradiation; - - /// - /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. - /// - public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Irradiation quantity. - /// - public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); - - /// - /// Get Irradiation in JoulesPerSquareMeter. - /// - public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); - - /// - /// Get Irradiation in KilowattHoursPerSquareMeter. - /// - public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); - - /// - /// Get Irradiation in WattHoursPerSquareMeter. - /// - public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. - /// - public static Irradiation Zero => new Irradiation(0, BaseUnit); - - /// - /// Get Irradiation from JoulesPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromJoulesPerSquareMeter(double joulespersquaremeter) -#else - public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) -#endif - { - double value = (double) joulespersquaremeter; - return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); - } - - /// - /// Get Irradiation from KilowattHoursPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromKilowattHoursPerSquareMeter(double kilowatthourspersquaremeter) -#else - public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) -#endif - { - double value = (double) kilowatthourspersquaremeter; - return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); - } - - /// - /// Get Irradiation from WattHoursPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromWattHoursPerSquareMeter(double watthourspersquaremeter) -#else - public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) -#endif - { - double value = (double) watthourspersquaremeter; - return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Irradiation unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Irradiation From(double value, IrradiationUnit fromUnit) -#else - public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) -#endif - { - return new Irradiation((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IrradiationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Irradiation)) throw new ArgumentException("Expected type Irradiation.", nameof(obj)); - - return CompareTo((Irradiation)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Irradiation other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Irradiation within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Irradiation other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiation. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradiationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Irradiation to another Irradiation with the unit representation . - /// - /// A Irradiation with the specified unit. - public Irradiation ToUnit(IrradiationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Irradiation(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 AsBaseUnit() - { - switch(Unit) - { - case IrradiationUnit.JoulePerSquareMeter: return _value; - case IrradiationUnit.KilowattHourPerSquareMeter: return (_value*3600d) * 1e3d; - case IrradiationUnit.WattHourPerSquareMeter: return _value*3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IrradiationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; - case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue/3600d) / 1e3d; - case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue/3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Irradiation Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Irradiation result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradiationUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out IrradiationUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Irradiation ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Irradiation result) - { - result = default(Irradiation); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static IrradiationUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == IrradiationUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradiationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out IrradiationUnit unit) - { - unit = IrradiationUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == IrradiationUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(IrradiationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Irradiation - /// - public static Irradiation MaxValue => new Irradiation(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Irradiation - /// - public static Irradiation MinValue => new Irradiation(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Irradiation.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Irradiation.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs b/Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs deleted file mode 100644 index 1c52767722..0000000000 --- a/Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class KinematicViscosity : IQuantity -#else - public partial struct KinematicViscosity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly KinematicViscosityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static KinematicViscosity() - { - BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - KinematicViscosity(double numericValue, KinematicViscosityUnit unit) - { - if(unit == KinematicViscosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.KinematicViscosity; - - /// - /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. - /// - public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the KinematicViscosity quantity. - /// - public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); - - /// - /// Get KinematicViscosity in Centistokes. - /// - public double Centistokes => As(KinematicViscosityUnit.Centistokes); - - /// - /// Get KinematicViscosity in Decistokes. - /// - public double Decistokes => As(KinematicViscosityUnit.Decistokes); - - /// - /// Get KinematicViscosity in Kilostokes. - /// - public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); - - /// - /// Get KinematicViscosity in Microstokes. - /// - public double Microstokes => As(KinematicViscosityUnit.Microstokes); - - /// - /// Get KinematicViscosity in Millistokes. - /// - public double Millistokes => As(KinematicViscosityUnit.Millistokes); - - /// - /// Get KinematicViscosity in Nanostokes. - /// - public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); - - /// - /// Get KinematicViscosity in SquareMetersPerSecond. - /// - public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); - - /// - /// Get KinematicViscosity in Stokes. - /// - public double Stokes => As(KinematicViscosityUnit.Stokes); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. - /// - public static KinematicViscosity Zero => new KinematicViscosity(0, BaseUnit); - - /// - /// Get KinematicViscosity from Centistokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromCentistokes(double centistokes) -#else - public static KinematicViscosity FromCentistokes(QuantityValue centistokes) -#endif - { - double value = (double) centistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); - } - - /// - /// Get KinematicViscosity from Decistokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromDecistokes(double decistokes) -#else - public static KinematicViscosity FromDecistokes(QuantityValue decistokes) -#endif - { - double value = (double) decistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); - } - - /// - /// Get KinematicViscosity from Kilostokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromKilostokes(double kilostokes) -#else - public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) -#endif - { - double value = (double) kilostokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); - } - - /// - /// Get KinematicViscosity from Microstokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromMicrostokes(double microstokes) -#else - public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) -#endif - { - double value = (double) microstokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); - } - - /// - /// Get KinematicViscosity from Millistokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromMillistokes(double millistokes) -#else - public static KinematicViscosity FromMillistokes(QuantityValue millistokes) -#endif - { - double value = (double) millistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); - } - - /// - /// Get KinematicViscosity from Nanostokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromNanostokes(double nanostokes) -#else - public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) -#endif - { - double value = (double) nanostokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); - } - - /// - /// Get KinematicViscosity from SquareMetersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromSquareMetersPerSecond(double squaremeterspersecond) -#else - public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) -#endif - { - double value = (double) squaremeterspersecond; - return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); - } - - /// - /// Get KinematicViscosity from Stokes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromStokes(double stokes) -#else - public static KinematicViscosity FromStokes(QuantityValue stokes) -#endif - { - double value = (double) stokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// KinematicViscosity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static KinematicViscosity From(double value, KinematicViscosityUnit fromUnit) -#else - public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) -#endif - { - return new KinematicViscosity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(KinematicViscosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is KinematicViscosity)) throw new ArgumentException("Expected type KinematicViscosity.", nameof(obj)); - - return CompareTo((KinematicViscosity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(KinematicViscosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another KinematicViscosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(KinematicViscosity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current KinematicViscosity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(KinematicViscosityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation . - /// - /// A KinematicViscosity with the specified unit. - public KinematicViscosity ToUnit(KinematicViscosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new KinematicViscosity(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 AsBaseUnit() - { - switch(Unit) - { - case KinematicViscosityUnit.Centistokes: return (_value/1e4) * 1e-2d; - case KinematicViscosityUnit.Decistokes: return (_value/1e4) * 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (_value/1e4) * 1e3d; - case KinematicViscosityUnit.Microstokes: return (_value/1e4) * 1e-6d; - case KinematicViscosityUnit.Millistokes: return (_value/1e4) * 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (_value/1e4) * 1e-9d; - case KinematicViscosityUnit.SquareMeterPerSecond: return _value; - case KinematicViscosityUnit.Stokes: return _value/1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(KinematicViscosityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case KinematicViscosityUnit.Centistokes: return (baseUnitValue*1e4) / 1e-2d; - case KinematicViscosityUnit.Decistokes: return (baseUnitValue*1e4) / 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (baseUnitValue*1e4) / 1e3d; - case KinematicViscosityUnit.Microstokes: return (baseUnitValue*1e4) / 1e-6d; - case KinematicViscosityUnit.Millistokes: return (baseUnitValue*1e4) / 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (baseUnitValue*1e4) / 1e-9d; - case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; - case KinematicViscosityUnit.Stokes: return baseUnitValue*1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 KinematicViscosity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out KinematicViscosity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static KinematicViscosityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static KinematicViscosity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out KinematicViscosity result) - { - result = default(KinematicViscosity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static KinematicViscosityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == KinematicViscosityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized KinematicViscosityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out KinematicViscosityUnit unit) - { - unit = KinematicViscosityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == KinematicViscosityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(KinematicViscosityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of KinematicViscosity - /// - public static KinematicViscosity MaxValue => new KinematicViscosity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of KinematicViscosity - /// - public static KinematicViscosity MinValue => new KinematicViscosity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => KinematicViscosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LapseRate.Common.g.cs b/Common/GeneratedCode/Quantities/LapseRate.Common.g.cs deleted file mode 100644 index 95ecc9ff70..0000000000 --- a/Common/GeneratedCode/Quantities/LapseRate.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LapseRate : IQuantity -#else - public partial struct LapseRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LapseRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LapseRate() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - LapseRate(double numericValue, LapseRateUnit unit) - { - if(unit == LapseRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LapseRate; - - /// - /// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value. - /// - public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LapseRate quantity. - /// - public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); - - /// - /// Get LapseRate in DegreesCelciusPerKilometer. - /// - public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. - /// - public static LapseRate Zero => new LapseRate(0, BaseUnit); - - /// - /// Get LapseRate from DegreesCelciusPerKilometer. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LapseRate FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) -#else - public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) -#endif - { - double value = (double) degreescelciusperkilometer; - return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LapseRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LapseRate From(double value, LapseRateUnit fromUnit) -#else - public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) -#endif - { - return new LapseRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LapseRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LapseRate)) throw new ArgumentException("Expected type LapseRate.", nameof(obj)); - - return CompareTo((LapseRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LapseRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LapseRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LapseRate. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LapseRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LapseRate to another LapseRate with the unit representation . - /// - /// A LapseRate with the specified unit. - public LapseRate ToUnit(LapseRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LapseRate(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 AsBaseUnit() - { - switch(Unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LapseRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 LapseRate Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LapseRate result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LapseRateUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out LapseRateUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static LapseRate ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LapseRate result) - { - result = default(LapseRate); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static LapseRateUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == LapseRateUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LapseRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LapseRateUnit unit) - { - unit = LapseRateUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == LapseRateUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LapseRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LapseRate - /// - public static LapseRate MaxValue => new LapseRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LapseRate - /// - public static LapseRate MinValue => new LapseRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LapseRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LapseRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Length.Common.g.cs b/Common/GeneratedCode/Quantities/Length.Common.g.cs deleted file mode 100644 index 5cf0e59579..0000000000 --- a/Common/GeneratedCode/Quantities/Length.Common.g.cs +++ /dev/null @@ -1,999 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Length : IQuantity -#else - public partial struct Length : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LengthUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Length() - { - BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Length(double numericValue, LengthUnit unit) - { - if(unit == LengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Length; - - /// - /// The base unit of Length, which is Meter. All conversions go via this value. - /// - public static LengthUnit BaseUnit => LengthUnit.Meter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Length quantity. - /// - public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); - - /// - /// Get Length in Centimeters. - /// - public double Centimeters => As(LengthUnit.Centimeter); - - /// - /// Get Length in Decimeters. - /// - public double Decimeters => As(LengthUnit.Decimeter); - - /// - /// Get Length in DtpPicas. - /// - public double DtpPicas => As(LengthUnit.DtpPica); - - /// - /// Get Length in DtpPoints. - /// - public double DtpPoints => As(LengthUnit.DtpPoint); - - /// - /// Get Length in Fathoms. - /// - public double Fathoms => As(LengthUnit.Fathom); - - /// - /// Get Length in Feet. - /// - public double Feet => As(LengthUnit.Foot); - - /// - /// Get Length in Inches. - /// - public double Inches => As(LengthUnit.Inch); - - /// - /// Get Length in Kilometers. - /// - public double Kilometers => As(LengthUnit.Kilometer); - - /// - /// Get Length in Meters. - /// - public double Meters => As(LengthUnit.Meter); - - /// - /// Get Length in Microinches. - /// - public double Microinches => As(LengthUnit.Microinch); - - /// - /// Get Length in Micrometers. - /// - public double Micrometers => As(LengthUnit.Micrometer); - - /// - /// Get Length in Mils. - /// - public double Mils => As(LengthUnit.Mil); - - /// - /// Get Length in Miles. - /// - public double Miles => As(LengthUnit.Mile); - - /// - /// Get Length in Millimeters. - /// - public double Millimeters => As(LengthUnit.Millimeter); - - /// - /// Get Length in Nanometers. - /// - public double Nanometers => As(LengthUnit.Nanometer); - - /// - /// Get Length in NauticalMiles. - /// - public double NauticalMiles => As(LengthUnit.NauticalMile); - - /// - /// Get Length in PrinterPicas. - /// - public double PrinterPicas => As(LengthUnit.PrinterPica); - - /// - /// Get Length in PrinterPoints. - /// - public double PrinterPoints => As(LengthUnit.PrinterPoint); - - /// - /// Get Length in Shackles. - /// - public double Shackles => As(LengthUnit.Shackle); - - /// - /// Get Length in Twips. - /// - public double Twips => As(LengthUnit.Twip); - - /// - /// Get Length in UsSurveyFeet. - /// - public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); - - /// - /// Get Length in Yards. - /// - public double Yards => As(LengthUnit.Yard); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Meter. - /// - public static Length Zero => new Length(0, BaseUnit); - - /// - /// Get Length from Centimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromCentimeters(double centimeters) -#else - public static Length FromCentimeters(QuantityValue centimeters) -#endif - { - double value = (double) centimeters; - return new Length(value, LengthUnit.Centimeter); - } - - /// - /// Get Length from Decimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDecimeters(double decimeters) -#else - public static Length FromDecimeters(QuantityValue decimeters) -#endif - { - double value = (double) decimeters; - return new Length(value, LengthUnit.Decimeter); - } - - /// - /// Get Length from DtpPicas. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDtpPicas(double dtppicas) -#else - public static Length FromDtpPicas(QuantityValue dtppicas) -#endif - { - double value = (double) dtppicas; - return new Length(value, LengthUnit.DtpPica); - } - - /// - /// Get Length from DtpPoints. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDtpPoints(double dtppoints) -#else - public static Length FromDtpPoints(QuantityValue dtppoints) -#endif - { - double value = (double) dtppoints; - return new Length(value, LengthUnit.DtpPoint); - } - - /// - /// Get Length from Fathoms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromFathoms(double fathoms) -#else - public static Length FromFathoms(QuantityValue fathoms) -#endif - { - double value = (double) fathoms; - return new Length(value, LengthUnit.Fathom); - } - - /// - /// Get Length from Feet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromFeet(double feet) -#else - public static Length FromFeet(QuantityValue feet) -#endif - { - double value = (double) feet; - return new Length(value, LengthUnit.Foot); - } - - /// - /// Get Length from Inches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromInches(double inches) -#else - public static Length FromInches(QuantityValue inches) -#endif - { - double value = (double) inches; - return new Length(value, LengthUnit.Inch); - } - - /// - /// Get Length from Kilometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromKilometers(double kilometers) -#else - public static Length FromKilometers(QuantityValue kilometers) -#endif - { - double value = (double) kilometers; - return new Length(value, LengthUnit.Kilometer); - } - - /// - /// Get Length from Meters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMeters(double meters) -#else - public static Length FromMeters(QuantityValue meters) -#endif - { - double value = (double) meters; - return new Length(value, LengthUnit.Meter); - } - - /// - /// Get Length from Microinches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMicroinches(double microinches) -#else - public static Length FromMicroinches(QuantityValue microinches) -#endif - { - double value = (double) microinches; - return new Length(value, LengthUnit.Microinch); - } - - /// - /// Get Length from Micrometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMicrometers(double micrometers) -#else - public static Length FromMicrometers(QuantityValue micrometers) -#endif - { - double value = (double) micrometers; - return new Length(value, LengthUnit.Micrometer); - } - - /// - /// Get Length from Mils. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMils(double mils) -#else - public static Length FromMils(QuantityValue mils) -#endif - { - double value = (double) mils; - return new Length(value, LengthUnit.Mil); - } - - /// - /// Get Length from Miles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMiles(double miles) -#else - public static Length FromMiles(QuantityValue miles) -#endif - { - double value = (double) miles; - return new Length(value, LengthUnit.Mile); - } - - /// - /// Get Length from Millimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMillimeters(double millimeters) -#else - public static Length FromMillimeters(QuantityValue millimeters) -#endif - { - double value = (double) millimeters; - return new Length(value, LengthUnit.Millimeter); - } - - /// - /// Get Length from Nanometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromNanometers(double nanometers) -#else - public static Length FromNanometers(QuantityValue nanometers) -#endif - { - double value = (double) nanometers; - return new Length(value, LengthUnit.Nanometer); - } - - /// - /// Get Length from NauticalMiles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromNauticalMiles(double nauticalmiles) -#else - public static Length FromNauticalMiles(QuantityValue nauticalmiles) -#endif - { - double value = (double) nauticalmiles; - return new Length(value, LengthUnit.NauticalMile); - } - - /// - /// Get Length from PrinterPicas. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromPrinterPicas(double printerpicas) -#else - public static Length FromPrinterPicas(QuantityValue printerpicas) -#endif - { - double value = (double) printerpicas; - return new Length(value, LengthUnit.PrinterPica); - } - - /// - /// Get Length from PrinterPoints. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromPrinterPoints(double printerpoints) -#else - public static Length FromPrinterPoints(QuantityValue printerpoints) -#endif - { - double value = (double) printerpoints; - return new Length(value, LengthUnit.PrinterPoint); - } - - /// - /// Get Length from Shackles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromShackles(double shackles) -#else - public static Length FromShackles(QuantityValue shackles) -#endif - { - double value = (double) shackles; - return new Length(value, LengthUnit.Shackle); - } - - /// - /// Get Length from Twips. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromTwips(double twips) -#else - public static Length FromTwips(QuantityValue twips) -#endif - { - double value = (double) twips; - return new Length(value, LengthUnit.Twip); - } - - /// - /// Get Length from UsSurveyFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromUsSurveyFeet(double ussurveyfeet) -#else - public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) -#endif - { - double value = (double) ussurveyfeet; - return new Length(value, LengthUnit.UsSurveyFoot); - } - - /// - /// Get Length from Yards. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromYards(double yards) -#else - public static Length FromYards(QuantityValue yards) -#endif - { - double value = (double) yards; - return new Length(value, LengthUnit.Yard); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Length unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Length From(double value, LengthUnit fromUnit) -#else - public static Length From(QuantityValue value, LengthUnit fromUnit) -#endif - { - return new Length((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Length)) throw new ArgumentException("Expected type Length.", nameof(obj)); - - return CompareTo((Length)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Length other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Length within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Length other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Length. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LengthUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Length to another Length with the unit representation . - /// - /// A Length with the specified unit. - public Length ToUnit(LengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Length(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 AsBaseUnit() - { - switch(Unit) - { - case LengthUnit.Centimeter: return (_value) * 1e-2d; - case LengthUnit.Decimeter: return (_value) * 1e-1d; - case LengthUnit.DtpPica: return _value/236.220472441; - case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; - case LengthUnit.Fathom: return _value*1.8288; - case LengthUnit.Foot: return _value*0.3048; - case LengthUnit.Inch: return _value*2.54e-2; - case LengthUnit.Kilometer: return (_value) * 1e3d; - case LengthUnit.Meter: return _value; - case LengthUnit.Microinch: return _value*2.54e-8; - case LengthUnit.Micrometer: return (_value) * 1e-6d; - case LengthUnit.Mil: return _value*2.54e-5; - case LengthUnit.Mile: return _value*1609.34; - case LengthUnit.Millimeter: return (_value) * 1e-3d; - case LengthUnit.Nanometer: return (_value) * 1e-9d; - case LengthUnit.NauticalMile: return _value*1852; - case LengthUnit.PrinterPica: return _value/237.106301584; - case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; - case LengthUnit.Shackle: return _value*27.432; - case LengthUnit.Twip: return _value/56692.913385826; - case LengthUnit.UsSurveyFoot: return _value*1200/3937; - case LengthUnit.Yard: return _value*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LengthUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; - case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; - case LengthUnit.DtpPica: return baseUnitValue*236.220472441; - case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; - case LengthUnit.Fathom: return baseUnitValue/1.8288; - case LengthUnit.Foot: return baseUnitValue/0.3048; - case LengthUnit.Inch: return baseUnitValue/2.54e-2; - case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; - case LengthUnit.Meter: return baseUnitValue; - case LengthUnit.Microinch: return baseUnitValue/2.54e-8; - case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; - case LengthUnit.Mil: return baseUnitValue/2.54e-5; - case LengthUnit.Mile: return baseUnitValue/1609.34; - case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; - case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; - case LengthUnit.NauticalMile: return baseUnitValue/1852; - case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; - case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; - case LengthUnit.Shackle: return baseUnitValue/27.432; - case LengthUnit.Twip: return baseUnitValue*56692.913385826; - case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; - case LengthUnit.Yard: return baseUnitValue/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Length Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Length result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LengthUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out LengthUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Length ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Length result) - { - result = default(Length); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static LengthUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == LengthUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LengthUnit unit) - { - unit = LengthUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == LengthUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LengthUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Length - /// - public static Length MaxValue => new Length(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Length - /// - public static Length MinValue => new Length(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Length.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Length.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Level.Common.g.cs b/Common/GeneratedCode/Quantities/Level.Common.g.cs deleted file mode 100644 index fb8bc39905..0000000000 --- a/Common/GeneratedCode/Quantities/Level.Common.g.cs +++ /dev/null @@ -1,558 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Level : IQuantity -#else - public partial struct Level : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LevelUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Level() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Level(double numericValue, LevelUnit unit) - { - if(unit == LevelUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Level; - - /// - /// The base unit of Level, which is Decibel. All conversions go via this value. - /// - public static LevelUnit BaseUnit => LevelUnit.Decibel; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Level quantity. - /// - public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); - - /// - /// Get Level in Decibels. - /// - public double Decibels => As(LevelUnit.Decibel); - - /// - /// Get Level in Nepers. - /// - public double Nepers => As(LevelUnit.Neper); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. - /// - public static Level Zero => new Level(0, BaseUnit); - - /// - /// Get Level from Decibels. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Level FromDecibels(double decibels) -#else - public static Level FromDecibels(QuantityValue decibels) -#endif - { - double value = (double) decibels; - return new Level(value, LevelUnit.Decibel); - } - - /// - /// Get Level from Nepers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Level FromNepers(double nepers) -#else - public static Level FromNepers(QuantityValue nepers) -#endif - { - double value = (double) nepers; - return new Level(value, LevelUnit.Neper); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Level unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Level From(double value, LevelUnit fromUnit) -#else - public static Level From(QuantityValue value, LevelUnit fromUnit) -#endif - { - return new Level((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LevelUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Level)) throw new ArgumentException("Expected type Level.", nameof(obj)); - - return CompareTo((Level)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Level other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Level within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Level other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Level. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LevelUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Level to another Level with the unit representation . - /// - /// A Level with the specified unit. - public Level ToUnit(LevelUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Level(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 AsBaseUnit() - { - switch(Unit) - { - case LevelUnit.Decibel: return _value; - case LevelUnit.Neper: return (1/0.115129254)*_value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LevelUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LevelUnit.Decibel: return baseUnitValue; - case LevelUnit.Neper: return 0.115129254*baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Level Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Level result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LevelUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out LevelUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Level ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) - { - result = default(Level); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static LevelUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == LevelUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LevelUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LevelUnit unit) - { - unit = LevelUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == LevelUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LevelUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Level - /// - public static Level MaxValue => new Level(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Level - /// - public static Level MinValue => new Level(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Level.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Level.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs b/Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs deleted file mode 100644 index bf93d8745a..0000000000 --- a/Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LinearDensity : IQuantity -#else - public partial struct LinearDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LinearDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LinearDensity() - { - BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - LinearDensity(double numericValue, LinearDensityUnit unit) - { - if(unit == LinearDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LinearDensity; - - /// - /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. - /// - public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LinearDensity quantity. - /// - public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); - - /// - /// Get LinearDensity in GramsPerMeter. - /// - public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); - - /// - /// Get LinearDensity in KilogramsPerMeter. - /// - public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); - - /// - /// Get LinearDensity in PoundsPerFoot. - /// - public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. - /// - public static LinearDensity Zero => new LinearDensity(0, BaseUnit); - - /// - /// Get LinearDensity from GramsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromGramsPerMeter(double gramspermeter) -#else - public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) -#endif - { - double value = (double) gramspermeter; - return new LinearDensity(value, LinearDensityUnit.GramPerMeter); - } - - /// - /// Get LinearDensity from KilogramsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromKilogramsPerMeter(double kilogramspermeter) -#else - public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) -#endif - { - double value = (double) kilogramspermeter; - return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); - } - - /// - /// Get LinearDensity from PoundsPerFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromPoundsPerFoot(double poundsperfoot) -#else - public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) -#endif - { - double value = (double) poundsperfoot; - return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LinearDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LinearDensity From(double value, LinearDensityUnit fromUnit) -#else - public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) -#endif - { - return new LinearDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LinearDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LinearDensity)) throw new ArgumentException("Expected type LinearDensity.", nameof(obj)); - - return CompareTo((LinearDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LinearDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LinearDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LinearDensity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LinearDensity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LinearDensity to another LinearDensity with the unit representation . - /// - /// A LinearDensity with the specified unit. - public LinearDensity ToUnit(LinearDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LinearDensity(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 AsBaseUnit() - { - switch(Unit) - { - case LinearDensityUnit.GramPerMeter: return _value*1e-3; - case LinearDensityUnit.KilogramPerMeter: return (_value*1e-3) * 1e3d; - case LinearDensityUnit.PoundPerFoot: return _value*1.48816394; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LinearDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LinearDensityUnit.GramPerMeter: return baseUnitValue/1e-3; - case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue/1e-3) / 1e3d; - case LinearDensityUnit.PoundPerFoot: return baseUnitValue/1.48816394; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 LinearDensity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LinearDensity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LinearDensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out LinearDensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static LinearDensity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LinearDensity result) - { - result = default(LinearDensity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static LinearDensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == LinearDensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LinearDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LinearDensityUnit unit) - { - unit = LinearDensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == LinearDensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LinearDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LinearDensity - /// - public static LinearDensity MaxValue => new LinearDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LinearDensity - /// - public static LinearDensity MinValue => new LinearDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LinearDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LinearDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs b/Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs deleted file mode 100644 index 1ec661ec2f..0000000000 --- a/Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LuminousFlux : IQuantity -#else - public partial struct LuminousFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminousFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LuminousFlux() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - LuminousFlux(double numericValue, LuminousFluxUnit unit) - { - if(unit == LuminousFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LuminousFlux; - - /// - /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. - /// - public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LuminousFlux quantity. - /// - public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); - - /// - /// Get LuminousFlux in Lumens. - /// - public double Lumens => As(LuminousFluxUnit.Lumen); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. - /// - public static LuminousFlux Zero => new LuminousFlux(0, BaseUnit); - - /// - /// Get LuminousFlux from Lumens. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LuminousFlux FromLumens(double lumens) -#else - public static LuminousFlux FromLumens(QuantityValue lumens) -#endif - { - double value = (double) lumens; - return new LuminousFlux(value, LuminousFluxUnit.Lumen); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LuminousFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) -#else - public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) -#endif - { - return new LuminousFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LuminousFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LuminousFlux)) throw new ArgumentException("Expected type LuminousFlux.", nameof(obj)); - - return CompareTo((LuminousFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LuminousFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LuminousFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousFlux. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LuminousFlux to another LuminousFlux with the unit representation . - /// - /// A LuminousFlux with the specified unit. - public LuminousFlux ToUnit(LuminousFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LuminousFlux(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 AsBaseUnit() - { - switch(Unit) - { - case LuminousFluxUnit.Lumen: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminousFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminousFluxUnit.Lumen: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 LuminousFlux Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LuminousFlux result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousFluxUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out LuminousFluxUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static LuminousFlux ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LuminousFlux result) - { - result = default(LuminousFlux); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static LuminousFluxUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == LuminousFluxUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LuminousFluxUnit unit) - { - unit = LuminousFluxUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == LuminousFluxUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LuminousFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LuminousFlux - /// - public static LuminousFlux MaxValue => new LuminousFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LuminousFlux - /// - public static LuminousFlux MinValue => new LuminousFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LuminousFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs b/Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs deleted file mode 100644 index 76d83c9d9e..0000000000 --- a/Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LuminousIntensity : IQuantity -#else - public partial struct LuminousIntensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminousIntensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LuminousIntensity() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - LuminousIntensity(double numericValue, LuminousIntensityUnit unit) - { - if(unit == LuminousIntensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LuminousIntensity; - - /// - /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. - /// - public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LuminousIntensity quantity. - /// - public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); - - /// - /// Get LuminousIntensity in Candela. - /// - public double Candela => As(LuminousIntensityUnit.Candela); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Candela. - /// - public static LuminousIntensity Zero => new LuminousIntensity(0, BaseUnit); - - /// - /// Get LuminousIntensity from Candela. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LuminousIntensity FromCandela(double candela) -#else - public static LuminousIntensity FromCandela(QuantityValue candela) -#endif - { - double value = (double) candela; - return new LuminousIntensity(value, LuminousIntensityUnit.Candela); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LuminousIntensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LuminousIntensity From(double value, LuminousIntensityUnit fromUnit) -#else - public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) -#endif - { - return new LuminousIntensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LuminousIntensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LuminousIntensity)) throw new ArgumentException("Expected type LuminousIntensity.", nameof(obj)); - - return CompareTo((LuminousIntensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LuminousIntensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LuminousIntensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LuminousIntensity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousIntensity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousIntensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation . - /// - /// A LuminousIntensity with the specified unit. - public LuminousIntensity ToUnit(LuminousIntensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LuminousIntensity(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 AsBaseUnit() - { - switch(Unit) - { - case LuminousIntensityUnit.Candela: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminousIntensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminousIntensityUnit.Candela: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 LuminousIntensity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LuminousIntensity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousIntensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static LuminousIntensity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LuminousIntensity result) - { - result = default(LuminousIntensity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static LuminousIntensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == LuminousIntensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousIntensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LuminousIntensityUnit unit) - { - unit = LuminousIntensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == LuminousIntensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LuminousIntensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LuminousIntensity - /// - public static LuminousIntensity MaxValue => new LuminousIntensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LuminousIntensity - /// - public static LuminousIntensity MinValue => new LuminousIntensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LuminousIntensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MagneticField.Common.g.cs b/Common/GeneratedCode/Quantities/MagneticField.Common.g.cs deleted file mode 100644 index 6d97502e59..0000000000 --- a/Common/GeneratedCode/Quantities/MagneticField.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MagneticField : IQuantity -#else - public partial struct MagneticField : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagneticFieldUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MagneticField() - { - BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MagneticField(double numericValue, MagneticFieldUnit unit) - { - if(unit == MagneticFieldUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MagneticField; - - /// - /// The base unit of MagneticField, which is Tesla. All conversions go via this value. - /// - public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MagneticField quantity. - /// - public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); - - /// - /// Get MagneticField in Teslas. - /// - public double Teslas => As(MagneticFieldUnit.Tesla); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. - /// - public static MagneticField Zero => new MagneticField(0, BaseUnit); - - /// - /// Get MagneticField from Teslas. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromTeslas(double teslas) -#else - public static MagneticField FromTeslas(QuantityValue teslas) -#endif - { - double value = (double) teslas; - return new MagneticField(value, MagneticFieldUnit.Tesla); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MagneticField unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MagneticField From(double value, MagneticFieldUnit fromUnit) -#else - public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) -#endif - { - return new MagneticField((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagneticFieldUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MagneticField)) throw new ArgumentException("Expected type MagneticField.", nameof(obj)); - - return CompareTo((MagneticField)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MagneticField other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MagneticField within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MagneticField other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticField. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFieldUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MagneticField to another MagneticField with the unit representation . - /// - /// A MagneticField with the specified unit. - public MagneticField ToUnit(MagneticFieldUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MagneticField(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 AsBaseUnit() - { - switch(Unit) - { - case MagneticFieldUnit.Tesla: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagneticFieldUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagneticFieldUnit.Tesla: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MagneticField Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MagneticField result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFieldUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MagneticFieldUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MagneticField ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MagneticField result) - { - result = default(MagneticField); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MagneticFieldUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MagneticFieldUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFieldUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MagneticFieldUnit unit) - { - unit = MagneticFieldUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MagneticFieldUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MagneticFieldUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MagneticField - /// - public static MagneticField MaxValue => new MagneticField(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MagneticField - /// - public static MagneticField MinValue => new MagneticField(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MagneticField.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MagneticField.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs b/Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs deleted file mode 100644 index 8fa9e01791..0000000000 --- a/Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MagneticFlux : IQuantity -#else - public partial struct MagneticFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagneticFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MagneticFlux() - { - BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MagneticFlux(double numericValue, MagneticFluxUnit unit) - { - if(unit == MagneticFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MagneticFlux; - - /// - /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. - /// - public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MagneticFlux quantity. - /// - public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); - - /// - /// Get MagneticFlux in Webers. - /// - public double Webers => As(MagneticFluxUnit.Weber); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Weber. - /// - public static MagneticFlux Zero => new MagneticFlux(0, BaseUnit); - - /// - /// Get MagneticFlux from Webers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticFlux FromWebers(double webers) -#else - public static MagneticFlux FromWebers(QuantityValue webers) -#endif - { - double value = (double) webers; - return new MagneticFlux(value, MagneticFluxUnit.Weber); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MagneticFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) -#else - public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) -#endif - { - return new MagneticFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagneticFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MagneticFlux)) throw new ArgumentException("Expected type MagneticFlux.", nameof(obj)); - - return CompareTo((MagneticFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MagneticFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MagneticFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticFlux. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MagneticFlux to another MagneticFlux with the unit representation . - /// - /// A MagneticFlux with the specified unit. - public MagneticFlux ToUnit(MagneticFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MagneticFlux(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 AsBaseUnit() - { - switch(Unit) - { - case MagneticFluxUnit.Weber: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagneticFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagneticFluxUnit.Weber: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MagneticFlux Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MagneticFlux result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFluxUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MagneticFluxUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MagneticFlux ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MagneticFlux result) - { - result = default(MagneticFlux); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MagneticFluxUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MagneticFluxUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MagneticFluxUnit unit) - { - unit = MagneticFluxUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MagneticFluxUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MagneticFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MagneticFlux - /// - public static MagneticFlux MaxValue => new MagneticFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MagneticFlux - /// - public static MagneticFlux MinValue => new MagneticFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MagneticFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Magnetization.Common.g.cs b/Common/GeneratedCode/Quantities/Magnetization.Common.g.cs deleted file mode 100644 index 4e2cf27b84..0000000000 --- a/Common/GeneratedCode/Quantities/Magnetization.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Magnetization : IQuantity -#else - public partial struct Magnetization : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagnetizationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Magnetization() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Magnetization(double numericValue, MagnetizationUnit unit) - { - if(unit == MagnetizationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Magnetization; - - /// - /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. - /// - public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Magnetization quantity. - /// - public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); - - /// - /// Get Magnetization in AmperesPerMeter. - /// - public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. - /// - public static Magnetization Zero => new Magnetization(0, BaseUnit); - - /// - /// Get Magnetization from AmperesPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Magnetization FromAmperesPerMeter(double amperespermeter) -#else - public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) -#endif - { - double value = (double) amperespermeter; - return new Magnetization(value, MagnetizationUnit.AmperePerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Magnetization unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Magnetization From(double value, MagnetizationUnit fromUnit) -#else - public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) -#endif - { - return new Magnetization((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagnetizationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Magnetization)) throw new ArgumentException("Expected type Magnetization.", nameof(obj)); - - return CompareTo((Magnetization)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Magnetization other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Magnetization within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Magnetization other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Magnetization. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagnetizationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Magnetization to another Magnetization with the unit representation . - /// - /// A Magnetization with the specified unit. - public Magnetization ToUnit(MagnetizationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Magnetization(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 AsBaseUnit() - { - switch(Unit) - { - case MagnetizationUnit.AmperePerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagnetizationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagnetizationUnit.AmperePerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Magnetization Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Magnetization result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagnetizationUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MagnetizationUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Magnetization ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Magnetization result) - { - result = default(Magnetization); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MagnetizationUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MagnetizationUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagnetizationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MagnetizationUnit unit) - { - unit = MagnetizationUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MagnetizationUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MagnetizationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Magnetization - /// - public static Magnetization MaxValue => new Magnetization(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Magnetization - /// - public static Magnetization MinValue => new Magnetization(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Magnetization.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Magnetization.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Mass.Common.g.cs b/Common/GeneratedCode/Quantities/Mass.Common.g.cs deleted file mode 100644 index eb7891bca8..0000000000 --- a/Common/GeneratedCode/Quantities/Mass.Common.g.cs +++ /dev/null @@ -1,999 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Mass : IQuantity -#else - public partial struct Mass : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Mass() - { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Mass(double numericValue, MassUnit unit) - { - if(unit == MassUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Mass; - - /// - /// The base unit of Mass, which is Kilogram. All conversions go via this value. - /// - public static MassUnit BaseUnit => MassUnit.Kilogram; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Mass quantity. - /// - public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); - - /// - /// Get Mass in Centigrams. - /// - public double Centigrams => As(MassUnit.Centigram); - - /// - /// Get Mass in Decagrams. - /// - public double Decagrams => As(MassUnit.Decagram); - - /// - /// Get Mass in Decigrams. - /// - public double Decigrams => As(MassUnit.Decigram); - - /// - /// Get Mass in Grams. - /// - public double Grams => As(MassUnit.Gram); - - /// - /// Get Mass in Hectograms. - /// - public double Hectograms => As(MassUnit.Hectogram); - - /// - /// Get Mass in Kilograms. - /// - public double Kilograms => As(MassUnit.Kilogram); - - /// - /// Get Mass in Kilopounds. - /// - public double Kilopounds => As(MassUnit.Kilopound); - - /// - /// Get Mass in Kilotonnes. - /// - public double Kilotonnes => As(MassUnit.Kilotonne); - - /// - /// Get Mass in LongHundredweight. - /// - public double LongHundredweight => As(MassUnit.LongHundredweight); - - /// - /// Get Mass in LongTons. - /// - public double LongTons => As(MassUnit.LongTon); - - /// - /// Get Mass in Megapounds. - /// - public double Megapounds => As(MassUnit.Megapound); - - /// - /// Get Mass in Megatonnes. - /// - public double Megatonnes => As(MassUnit.Megatonne); - - /// - /// Get Mass in Micrograms. - /// - public double Micrograms => As(MassUnit.Microgram); - - /// - /// Get Mass in Milligrams. - /// - public double Milligrams => As(MassUnit.Milligram); - - /// - /// Get Mass in Nanograms. - /// - public double Nanograms => As(MassUnit.Nanogram); - - /// - /// Get Mass in Ounces. - /// - public double Ounces => As(MassUnit.Ounce); - - /// - /// Get Mass in Pounds. - /// - public double Pounds => As(MassUnit.Pound); - - /// - /// Get Mass in ShortHundredweight. - /// - public double ShortHundredweight => As(MassUnit.ShortHundredweight); - - /// - /// Get Mass in ShortTons. - /// - public double ShortTons => As(MassUnit.ShortTon); - - /// - /// Get Mass in Slugs. - /// - public double Slugs => As(MassUnit.Slug); - - /// - /// Get Mass in Stone. - /// - public double Stone => As(MassUnit.Stone); - - /// - /// Get Mass in Tonnes. - /// - public double Tonnes => As(MassUnit.Tonne); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. - /// - public static Mass Zero => new Mass(0, BaseUnit); - - /// - /// Get Mass from Centigrams. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromCentigrams(double centigrams) -#else - public static Mass FromCentigrams(QuantityValue centigrams) -#endif - { - double value = (double) centigrams; - return new Mass(value, MassUnit.Centigram); - } - - /// - /// Get Mass from Decagrams. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromDecagrams(double decagrams) -#else - public static Mass FromDecagrams(QuantityValue decagrams) -#endif - { - double value = (double) decagrams; - return new Mass(value, MassUnit.Decagram); - } - - /// - /// Get Mass from Decigrams. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromDecigrams(double decigrams) -#else - public static Mass FromDecigrams(QuantityValue decigrams) -#endif - { - double value = (double) decigrams; - return new Mass(value, MassUnit.Decigram); - } - - /// - /// Get Mass from Grams. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromGrams(double grams) -#else - public static Mass FromGrams(QuantityValue grams) -#endif - { - double value = (double) grams; - return new Mass(value, MassUnit.Gram); - } - - /// - /// Get Mass from Hectograms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromHectograms(double hectograms) -#else - public static Mass FromHectograms(QuantityValue hectograms) -#endif - { - double value = (double) hectograms; - return new Mass(value, MassUnit.Hectogram); - } - - /// - /// Get Mass from Kilograms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilograms(double kilograms) -#else - public static Mass FromKilograms(QuantityValue kilograms) -#endif - { - double value = (double) kilograms; - return new Mass(value, MassUnit.Kilogram); - } - - /// - /// Get Mass from Kilopounds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilopounds(double kilopounds) -#else - public static Mass FromKilopounds(QuantityValue kilopounds) -#endif - { - double value = (double) kilopounds; - return new Mass(value, MassUnit.Kilopound); - } - - /// - /// Get Mass from Kilotonnes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilotonnes(double kilotonnes) -#else - public static Mass FromKilotonnes(QuantityValue kilotonnes) -#endif - { - double value = (double) kilotonnes; - return new Mass(value, MassUnit.Kilotonne); - } - - /// - /// Get Mass from LongHundredweight. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromLongHundredweight(double longhundredweight) -#else - public static Mass FromLongHundredweight(QuantityValue longhundredweight) -#endif - { - double value = (double) longhundredweight; - return new Mass(value, MassUnit.LongHundredweight); - } - - /// - /// Get Mass from LongTons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromLongTons(double longtons) -#else - public static Mass FromLongTons(QuantityValue longtons) -#endif - { - double value = (double) longtons; - return new Mass(value, MassUnit.LongTon); - } - - /// - /// Get Mass from Megapounds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMegapounds(double megapounds) -#else - public static Mass FromMegapounds(QuantityValue megapounds) -#endif - { - double value = (double) megapounds; - return new Mass(value, MassUnit.Megapound); - } - - /// - /// Get Mass from Megatonnes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMegatonnes(double megatonnes) -#else - public static Mass FromMegatonnes(QuantityValue megatonnes) -#endif - { - double value = (double) megatonnes; - return new Mass(value, MassUnit.Megatonne); - } - - /// - /// Get Mass from Micrograms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMicrograms(double micrograms) -#else - public static Mass FromMicrograms(QuantityValue micrograms) -#endif - { - double value = (double) micrograms; - return new Mass(value, MassUnit.Microgram); - } - - /// - /// Get Mass from Milligrams. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMilligrams(double milligrams) -#else - public static Mass FromMilligrams(QuantityValue milligrams) -#endif - { - double value = (double) milligrams; - return new Mass(value, MassUnit.Milligram); - } - - /// - /// Get Mass from Nanograms. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromNanograms(double nanograms) -#else - public static Mass FromNanograms(QuantityValue nanograms) -#endif - { - double value = (double) nanograms; - return new Mass(value, MassUnit.Nanogram); - } - - /// - /// Get Mass from Ounces. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromOunces(double ounces) -#else - public static Mass FromOunces(QuantityValue ounces) -#endif - { - double value = (double) ounces; - return new Mass(value, MassUnit.Ounce); - } - - /// - /// Get Mass from Pounds. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromPounds(double pounds) -#else - public static Mass FromPounds(QuantityValue pounds) -#endif - { - double value = (double) pounds; - return new Mass(value, MassUnit.Pound); - } - - /// - /// Get Mass from ShortHundredweight. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromShortHundredweight(double shorthundredweight) -#else - public static Mass FromShortHundredweight(QuantityValue shorthundredweight) -#endif - { - double value = (double) shorthundredweight; - return new Mass(value, MassUnit.ShortHundredweight); - } - - /// - /// Get Mass from ShortTons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromShortTons(double shorttons) -#else - public static Mass FromShortTons(QuantityValue shorttons) -#endif - { - double value = (double) shorttons; - return new Mass(value, MassUnit.ShortTon); - } - - /// - /// Get Mass from Slugs. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromSlugs(double slugs) -#else - public static Mass FromSlugs(QuantityValue slugs) -#endif - { - double value = (double) slugs; - return new Mass(value, MassUnit.Slug); - } - - /// - /// Get Mass from Stone. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromStone(double stone) -#else - public static Mass FromStone(QuantityValue stone) -#endif - { - double value = (double) stone; - return new Mass(value, MassUnit.Stone); - } - - /// - /// Get Mass from Tonnes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromTonnes(double tonnes) -#else - public static Mass FromTonnes(QuantityValue tonnes) -#endif - { - double value = (double) tonnes; - return new Mass(value, MassUnit.Tonne); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Mass unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Mass From(double value, MassUnit fromUnit) -#else - public static Mass From(QuantityValue value, MassUnit fromUnit) -#endif - { - return new Mass((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Mass)) throw new ArgumentException("Expected type Mass.", nameof(obj)); - - return CompareTo((Mass)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Mass other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Mass within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Mass. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Mass to another Mass with the unit representation . - /// - /// A Mass with the specified unit. - public Mass ToUnit(MassUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Mass(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 AsBaseUnit() - { - switch(Unit) - { - case MassUnit.Centigram: return (_value/1e3) * 1e-2d; - case MassUnit.Decagram: return (_value/1e3) * 1e1d; - case MassUnit.Decigram: return (_value/1e3) * 1e-1d; - case MassUnit.Gram: return _value/1e3; - case MassUnit.Hectogram: return (_value/1e3) * 1e2d; - case MassUnit.Kilogram: return (_value/1e3) * 1e3d; - case MassUnit.Kilopound: return (_value*0.45359237) * 1e3d; - case MassUnit.Kilotonne: return (_value*1e3) * 1e3d; - case MassUnit.LongHundredweight: return _value/0.01968413055222121; - case MassUnit.LongTon: return _value*1.0160469088e3; - case MassUnit.Megapound: return (_value*0.45359237) * 1e6d; - case MassUnit.Megatonne: return (_value*1e3) * 1e6d; - case MassUnit.Microgram: return (_value/1e3) * 1e-6d; - case MassUnit.Milligram: return (_value/1e3) * 1e-3d; - case MassUnit.Nanogram: return (_value/1e3) * 1e-9d; - case MassUnit.Ounce: return _value/35.2739619; - case MassUnit.Pound: return _value*0.45359237; - case MassUnit.ShortHundredweight: return _value/0.022046226218487758; - case MassUnit.ShortTon: return _value*9.0718474e2; - case MassUnit.Slug: return _value/6.852176556196105e-2; - case MassUnit.Stone: return _value/0.1574731728702698; - case MassUnit.Tonne: return _value*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassUnit.Centigram: return (baseUnitValue*1e3) / 1e-2d; - case MassUnit.Decagram: return (baseUnitValue*1e3) / 1e1d; - case MassUnit.Decigram: return (baseUnitValue*1e3) / 1e-1d; - case MassUnit.Gram: return baseUnitValue*1e3; - case MassUnit.Hectogram: return (baseUnitValue*1e3) / 1e2d; - case MassUnit.Kilogram: return (baseUnitValue*1e3) / 1e3d; - case MassUnit.Kilopound: return (baseUnitValue/0.45359237) / 1e3d; - case MassUnit.Kilotonne: return (baseUnitValue/1e3) / 1e3d; - case MassUnit.LongHundredweight: return baseUnitValue*0.01968413055222121; - case MassUnit.LongTon: return baseUnitValue/1.0160469088e3; - case MassUnit.Megapound: return (baseUnitValue/0.45359237) / 1e6d; - case MassUnit.Megatonne: return (baseUnitValue/1e3) / 1e6d; - case MassUnit.Microgram: return (baseUnitValue*1e3) / 1e-6d; - case MassUnit.Milligram: return (baseUnitValue*1e3) / 1e-3d; - case MassUnit.Nanogram: return (baseUnitValue*1e3) / 1e-9d; - case MassUnit.Ounce: return baseUnitValue*35.2739619; - case MassUnit.Pound: return baseUnitValue/0.45359237; - case MassUnit.ShortHundredweight: return baseUnitValue*0.022046226218487758; - case MassUnit.ShortTon: return baseUnitValue/9.0718474e2; - case MassUnit.Slug: return baseUnitValue*6.852176556196105e-2; - case MassUnit.Stone: return baseUnitValue*0.1574731728702698; - case MassUnit.Tonne: return baseUnitValue/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Mass Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Mass result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MassUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Mass ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Mass result) - { - result = default(Mass); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MassUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MassUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MassUnit unit) - { - unit = MassUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MassUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Mass - /// - public static Mass MaxValue => new Mass(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Mass - /// - public static Mass MinValue => new Mass(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Mass.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Mass.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MassFlow.Common.g.cs b/Common/GeneratedCode/Quantities/MassFlow.Common.g.cs deleted file mode 100644 index e27aa6b919..0000000000 --- a/Common/GeneratedCode/Quantities/MassFlow.Common.g.cs +++ /dev/null @@ -1,845 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MassFlow : IQuantity -#else - public partial struct MassFlow : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFlowUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MassFlow() - { - BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MassFlow(double numericValue, MassFlowUnit unit) - { - if(unit == MassFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MassFlow; - - /// - /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. - /// - public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MassFlow quantity. - /// - public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); - - /// - /// Get MassFlow in CentigramsPerSecond. - /// - public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); - - /// - /// Get MassFlow in DecagramsPerSecond. - /// - public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); - - /// - /// Get MassFlow in DecigramsPerSecond. - /// - public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); - - /// - /// Get MassFlow in GramsPerSecond. - /// - public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); - - /// - /// Get MassFlow in HectogramsPerSecond. - /// - public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); - - /// - /// Get MassFlow in KilogramsPerHour. - /// - public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); - - /// - /// Get MassFlow in KilogramsPerSecond. - /// - public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); - - /// - /// Get MassFlow in MegapoundsPerHour. - /// - public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); - - /// - /// Get MassFlow in MicrogramsPerSecond. - /// - public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); - - /// - /// Get MassFlow in MilligramsPerSecond. - /// - public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); - - /// - /// Get MassFlow in NanogramsPerSecond. - /// - public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); - - /// - /// Get MassFlow in PoundsPerHour. - /// - public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); - - /// - /// Get MassFlow in ShortTonsPerHour. - /// - public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); - - /// - /// Get MassFlow in TonnesPerDay. - /// - public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); - - /// - /// Get MassFlow in TonnesPerHour. - /// - public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. - /// - public static MassFlow Zero => new MassFlow(0, BaseUnit); - - /// - /// Get MassFlow from CentigramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromCentigramsPerSecond(double centigramspersecond) -#else - public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) -#endif - { - double value = (double) centigramspersecond; - return new MassFlow(value, MassFlowUnit.CentigramPerSecond); - } - - /// - /// Get MassFlow from DecagramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecagramsPerSecond(double decagramspersecond) -#else - public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) -#endif - { - double value = (double) decagramspersecond; - return new MassFlow(value, MassFlowUnit.DecagramPerSecond); - } - - /// - /// Get MassFlow from DecigramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecigramsPerSecond(double decigramspersecond) -#else - public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) -#endif - { - double value = (double) decigramspersecond; - return new MassFlow(value, MassFlowUnit.DecigramPerSecond); - } - - /// - /// Get MassFlow from GramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromGramsPerSecond(double gramspersecond) -#else - public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) -#endif - { - double value = (double) gramspersecond; - return new MassFlow(value, MassFlowUnit.GramPerSecond); - } - - /// - /// Get MassFlow from HectogramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromHectogramsPerSecond(double hectogramspersecond) -#else - public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) -#endif - { - double value = (double) hectogramspersecond; - return new MassFlow(value, MassFlowUnit.HectogramPerSecond); - } - - /// - /// Get MassFlow from KilogramsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerHour(double kilogramsperhour) -#else - public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) -#endif - { - double value = (double) kilogramsperhour; - return new MassFlow(value, MassFlowUnit.KilogramPerHour); - } - - /// - /// Get MassFlow from KilogramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerSecond(double kilogramspersecond) -#else - public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) -#endif - { - double value = (double) kilogramspersecond; - return new MassFlow(value, MassFlowUnit.KilogramPerSecond); - } - - /// - /// Get MassFlow from MegapoundsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerHour(double megapoundsperhour) -#else - public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) -#endif - { - double value = (double) megapoundsperhour; - return new MassFlow(value, MassFlowUnit.MegapoundPerHour); - } - - /// - /// Get MassFlow from MicrogramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMicrogramsPerSecond(double microgramspersecond) -#else - public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) -#endif - { - double value = (double) microgramspersecond; - return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); - } - - /// - /// Get MassFlow from MilligramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMilligramsPerSecond(double milligramspersecond) -#else - public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) -#endif - { - double value = (double) milligramspersecond; - return new MassFlow(value, MassFlowUnit.MilligramPerSecond); - } - - /// - /// Get MassFlow from NanogramsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromNanogramsPerSecond(double nanogramspersecond) -#else - public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) -#endif - { - double value = (double) nanogramspersecond; - return new MassFlow(value, MassFlowUnit.NanogramPerSecond); - } - - /// - /// Get MassFlow from PoundsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerHour(double poundsperhour) -#else - public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) -#endif - { - double value = (double) poundsperhour; - return new MassFlow(value, MassFlowUnit.PoundPerHour); - } - - /// - /// Get MassFlow from ShortTonsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromShortTonsPerHour(double shorttonsperhour) -#else - public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) -#endif - { - double value = (double) shorttonsperhour; - return new MassFlow(value, MassFlowUnit.ShortTonPerHour); - } - - /// - /// Get MassFlow from TonnesPerDay. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromTonnesPerDay(double tonnesperday) -#else - public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) -#endif - { - double value = (double) tonnesperday; - return new MassFlow(value, MassFlowUnit.TonnePerDay); - } - - /// - /// Get MassFlow from TonnesPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromTonnesPerHour(double tonnesperhour) -#else - public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) -#endif - { - double value = (double) tonnesperhour; - return new MassFlow(value, MassFlowUnit.TonnePerHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFlow unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFlow From(double value, MassFlowUnit fromUnit) -#else - public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) -#endif - { - return new MassFlow((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MassFlow)) throw new ArgumentException("Expected type MassFlow.", nameof(obj)); - - return CompareTo((MassFlow)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MassFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlow. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFlowUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFlow to another MassFlow with the unit representation . - /// - /// A MassFlow with the specified unit. - public MassFlow ToUnit(MassFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFlow(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 AsBaseUnit() - { - switch(Unit) - { - case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; - case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; - case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; - case MassFlowUnit.GramPerSecond: return _value; - case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; - case MassFlowUnit.KilogramPerHour: return _value/3.6; - case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; - case MassFlowUnit.MegapoundPerHour: return (_value/7.93664) * 1e6d; - case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; - case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; - case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; - case MassFlowUnit.PoundPerHour: return _value/7.93664; - case MassFlowUnit.ShortTonPerHour: return _value*251.9957611; - case MassFlowUnit.TonnePerDay: return _value/0.0864000; - case MassFlowUnit.TonnePerHour: return 1000*_value/3.6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFlowUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; - case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; - case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; - case MassFlowUnit.GramPerSecond: return baseUnitValue; - case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; - case MassFlowUnit.KilogramPerHour: return baseUnitValue*3.6; - case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; - case MassFlowUnit.MegapoundPerHour: return (baseUnitValue*7.93664) / 1e6d; - case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; - case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; - case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; - case MassFlowUnit.PoundPerHour: return baseUnitValue*7.93664; - case MassFlowUnit.ShortTonPerHour: return baseUnitValue/251.9957611; - case MassFlowUnit.TonnePerDay: return baseUnitValue*0.0864000; - case MassFlowUnit.TonnePerHour: return baseUnitValue*3.6/1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MassFlow Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFlow result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFlowUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MassFlowUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MassFlow ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassFlow result) - { - result = default(MassFlow); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MassFlowUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MassFlowUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MassFlowUnit unit) - { - unit = MassFlowUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MassFlowUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassFlowUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MassFlow - /// - public static MassFlow MaxValue => new MassFlow(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MassFlow - /// - public static MassFlow MinValue => new MassFlow(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MassFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFlow.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MassFlux.Common.g.cs b/Common/GeneratedCode/Quantities/MassFlux.Common.g.cs deleted file mode 100644 index b23e5aca4b..0000000000 --- a/Common/GeneratedCode/Quantities/MassFlux.Common.g.cs +++ /dev/null @@ -1,559 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mass flux is the mass flow rate per unit area. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MassFlux : IQuantity -#else - public partial struct MassFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MassFlux() - { - BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MassFlux(double numericValue, MassFluxUnit unit) - { - if(unit == MassFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MassFlux; - - /// - /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. - /// - public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MassFlux quantity. - /// - public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); - - /// - /// Get MassFlux in GramsPerSecondPerSquareMeter. - /// - public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); - - /// - /// Get MassFlux in KilogramsPerSecondPerSquareMeter. - /// - public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. - /// - public static MassFlux Zero => new MassFlux(0, BaseUnit); - - /// - /// Get MassFlux from GramsPerSecondPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerSecondPerSquareMeter(double gramspersecondpersquaremeter) -#else - public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) -#endif - { - double value = (double) gramspersecondpersquaremeter; - return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); - } - - /// - /// Get MassFlux from KilogramsPerSecondPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerSecondPerSquareMeter(double kilogramspersecondpersquaremeter) -#else - public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) -#endif - { - double value = (double) kilogramspersecondpersquaremeter; - return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFlux From(double value, MassFluxUnit fromUnit) -#else - public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) -#endif - { - return new MassFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MassFlux)) throw new ArgumentException("Expected type MassFlux.", nameof(obj)); - - return CompareTo((MassFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MassFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlux. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFlux to another MassFlux with the unit representation . - /// - /// A MassFlux with the specified unit. - public MassFlux ToUnit(MassFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFlux(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 AsBaseUnit() - { - switch(Unit) - { - case MassFluxUnit.GramPerSecondPerSquareMeter: return _value/1e3; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value/1e3) * 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue*1e3; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue*1e3) / 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MassFlux Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFlux result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFluxUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MassFluxUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MassFlux ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassFlux result) - { - result = default(MassFlux); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MassFluxUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MassFluxUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MassFluxUnit unit) - { - unit = MassFluxUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MassFluxUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MassFlux - /// - public static MassFlux MaxValue => new MassFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MassFlux - /// - public static MassFlux MinValue => new MassFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MassFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs b/Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs deleted file mode 100644 index 00650df202..0000000000 --- a/Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs +++ /dev/null @@ -1,1131 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A property of body reflects how its mass is distributed with regard to an axis. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MassMomentOfInertia : IQuantity -#else - public partial struct MassMomentOfInertia : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassMomentOfInertiaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MassMomentOfInertia() - { - BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MassMomentOfInertia(double numericValue, MassMomentOfInertiaUnit unit) - { - if(unit == MassMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MassMomentOfInertia; - - /// - /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. - /// - public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MassMomentOfInertia quantity. - /// - public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); - - /// - /// Get MassMomentOfInertia in GramSquareCentimeters. - /// - public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); - - /// - /// Get MassMomentOfInertia in GramSquareDecimeters. - /// - public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); - - /// - /// Get MassMomentOfInertia in GramSquareMeters. - /// - public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); - - /// - /// Get MassMomentOfInertia in GramSquareMillimeters. - /// - public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareCentimeters. - /// - public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareDecimeters. - /// - public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareMeters. - /// - public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareMillimeters. - /// - public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareCentimeters. - /// - public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareDecimeters. - /// - public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareMeters. - /// - public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareMilimeters. - /// - public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareCentimeters. - /// - public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareDecimeters. - /// - public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareMeters. - /// - public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareMilimeters. - /// - public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareCentimeters. - /// - public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareDecimeters. - /// - public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareMeters. - /// - public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareMillimeters. - /// - public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); - - /// - /// Get MassMomentOfInertia in PoundSquareFeet. - /// - public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); - - /// - /// Get MassMomentOfInertia in PoundSquareInches. - /// - public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); - - /// - /// Get MassMomentOfInertia in SlugSquareFeet. - /// - public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); - - /// - /// Get MassMomentOfInertia in SlugSquareInches. - /// - public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); - - /// - /// Get MassMomentOfInertia in TonneSquareCentimeters. - /// - public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); - - /// - /// Get MassMomentOfInertia in TonneSquareDecimeters. - /// - public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); - - /// - /// Get MassMomentOfInertia in TonneSquareMeters. - /// - public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); - - /// - /// Get MassMomentOfInertia in TonneSquareMilimeters. - /// - public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. - /// - public static MassMomentOfInertia Zero => new MassMomentOfInertia(0, BaseUnit); - - /// - /// Get MassMomentOfInertia from GramSquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareCentimeters(double gramsquarecentimeters) -#else - public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) -#endif - { - double value = (double) gramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from GramSquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareDecimeters(double gramsquaredecimeters) -#else - public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) -#endif - { - double value = (double) gramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from GramSquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareMeters(double gramsquaremeters) -#else - public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) -#endif - { - double value = (double) gramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); - } - - /// - /// Get MassMomentOfInertia from GramSquareMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareMillimeters(double gramsquaremillimeters) -#else - public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) -#endif - { - double value = (double) gramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareCentimeters(double kilogramsquarecentimeters) -#else - public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) -#endif - { - double value = (double) kilogramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareDecimeters(double kilogramsquaredecimeters) -#else - public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) -#endif - { - double value = (double) kilogramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareMeters(double kilogramsquaremeters) -#else - public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) -#endif - { - double value = (double) kilogramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareMillimeters(double kilogramsquaremillimeters) -#else - public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) -#endif - { - double value = (double) kilogramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareCentimeters(double kilotonnesquarecentimeters) -#else - public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) -#endif - { - double value = (double) kilotonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareDecimeters(double kilotonnesquaredecimeters) -#else - public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) -#endif - { - double value = (double) kilotonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareMeters(double kilotonnesquaremeters) -#else - public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) -#endif - { - double value = (double) kilotonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareMilimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareMilimeters(double kilotonnesquaremilimeters) -#else - public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) -#endif - { - double value = (double) kilotonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareCentimeters(double megatonnesquarecentimeters) -#else - public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) -#endif - { - double value = (double) megatonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareDecimeters(double megatonnesquaredecimeters) -#else - public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) -#endif - { - double value = (double) megatonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareMeters(double megatonnesquaremeters) -#else - public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) -#endif - { - double value = (double) megatonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareMilimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareMilimeters(double megatonnesquaremilimeters) -#else - public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) -#endif - { - double value = (double) megatonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareCentimeters(double milligramsquarecentimeters) -#else - public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) -#endif - { - double value = (double) milligramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareDecimeters(double milligramsquaredecimeters) -#else - public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) -#endif - { - double value = (double) milligramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareMeters(double milligramsquaremeters) -#else - public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) -#endif - { - double value = (double) milligramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareMillimeters(double milligramsquaremillimeters) -#else - public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) -#endif - { - double value = (double) milligramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); - } - - /// - /// Get MassMomentOfInertia from PoundSquareFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromPoundSquareFeet(double poundsquarefeet) -#else - public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) -#endif - { - double value = (double) poundsquarefeet; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); - } - - /// - /// Get MassMomentOfInertia from PoundSquareInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromPoundSquareInches(double poundsquareinches) -#else - public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) -#endif - { - double value = (double) poundsquareinches; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); - } - - /// - /// Get MassMomentOfInertia from SlugSquareFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromSlugSquareFeet(double slugsquarefeet) -#else - public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefeet) -#endif - { - double value = (double) slugsquarefeet; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); - } - - /// - /// Get MassMomentOfInertia from SlugSquareInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromSlugSquareInches(double slugsquareinches) -#else - public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquareinches) -#endif - { - double value = (double) slugsquareinches; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); - } - - /// - /// Get MassMomentOfInertia from TonneSquareCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareCentimeters(double tonnesquarecentimeters) -#else - public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) -#endif - { - double value = (double) tonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from TonneSquareDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareDecimeters(double tonnesquaredecimeters) -#else - public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) -#endif - { - double value = (double) tonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from TonneSquareMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareMeters(double tonnesquaremeters) -#else - public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) -#endif - { - double value = (double) tonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); - } - - /// - /// Get MassMomentOfInertia from TonneSquareMilimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareMilimeters(double tonnesquaremilimeters) -#else - public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) -#endif - { - double value = (double) tonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassMomentOfInertia unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fromUnit) -#else - public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) -#endif - { - return new MassMomentOfInertia((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MassMomentOfInertia)) throw new ArgumentException("Expected type MassMomentOfInertia.", nameof(obj)); - - return CompareTo((MassMomentOfInertia)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MassMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassMomentOfInertia. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassMomentOfInertiaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . - /// - /// A MassMomentOfInertia with the specified unit. - public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassMomentOfInertia(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 AsBaseUnit() - { - switch(Unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return _value/1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return _value/1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return _value/1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return _value/1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (_value/1e7) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (_value/1e5) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (_value/1e3) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (_value/1e9) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (_value/1e1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (_value/1e-1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (_value/1e-3) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (_value/1e3) * 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (_value/1e1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (_value/1e-1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (_value/1e-3) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (_value/1e3) * 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (_value/1e7) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (_value/1e5) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (_value/1e3) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (_value/1e9) * 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return _value*4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return _value*2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return _value*1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return _value*9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return _value/1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return _value/1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return _value/1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return _value/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassMomentOfInertiaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return baseUnitValue*1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return baseUnitValue*1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return baseUnitValue*1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return baseUnitValue*1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (baseUnitValue*1e7) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (baseUnitValue*1e5) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (baseUnitValue*1e3) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (baseUnitValue*1e9) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (baseUnitValue*1e1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (baseUnitValue*1e-3) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (baseUnitValue*1e3) / 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (baseUnitValue*1e1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (baseUnitValue*1e-3) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (baseUnitValue*1e3) / 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (baseUnitValue*1e7) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (baseUnitValue*1e5) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (baseUnitValue*1e3) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (baseUnitValue*1e9) / 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return baseUnitValue/4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return baseUnitValue/2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return baseUnitValue/1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return baseUnitValue/9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return baseUnitValue*1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return baseUnitValue*1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return baseUnitValue*1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return baseUnitValue*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MassMomentOfInertia Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MassMomentOfInertia ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassMomentOfInertia result) - { - result = default(MassMomentOfInertia); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MassMomentOfInertiaUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MassMomentOfInertiaUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassMomentOfInertiaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MassMomentOfInertiaUnit unit) - { - unit = MassMomentOfInertiaUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MassMomentOfInertiaUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassMomentOfInertiaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MassMomentOfInertia - /// - public static MassMomentOfInertia MaxValue => new MassMomentOfInertia(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MassMomentOfInertia - /// - public static MassMomentOfInertia MinValue => new MassMomentOfInertia(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MassMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs deleted file mode 100644 index c7976e833c..0000000000 --- a/Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar energy is the amount of energy stored in 1 mole of a substance. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MolarEnergy : IQuantity -#else - public partial struct MolarEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MolarEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MolarEnergy(double numericValue, MolarEnergyUnit unit) - { - if(unit == MolarEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MolarEnergy; - - /// - /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. - /// - public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MolarEnergy quantity. - /// - public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); - - /// - /// Get MolarEnergy in JoulesPerMole. - /// - public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); - - /// - /// Get MolarEnergy in KilojoulesPerMole. - /// - public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); - - /// - /// Get MolarEnergy in MegajoulesPerMole. - /// - public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. - /// - public static MolarEnergy Zero => new MolarEnergy(0, BaseUnit); - - /// - /// Get MolarEnergy from JoulesPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromJoulesPerMole(double joulespermole) -#else - public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) -#endif - { - double value = (double) joulespermole; - return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); - } - - /// - /// Get MolarEnergy from KilojoulesPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromKilojoulesPerMole(double kilojoulespermole) -#else - public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) -#endif - { - double value = (double) kilojoulespermole; - return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); - } - - /// - /// Get MolarEnergy from MegajoulesPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromMegajoulesPerMole(double megajoulespermole) -#else - public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) -#endif - { - double value = (double) megajoulespermole; - return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) -#else - public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) -#endif - { - return new MolarEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MolarEnergy)) throw new ArgumentException("Expected type MolarEnergy.", nameof(obj)); - - return CompareTo((MolarEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MolarEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MolarEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarEnergy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEnergy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarEnergy to another MolarEnergy with the unit representation . - /// - /// A MolarEnergy with the specified unit. - public MolarEnergy ToUnit(MolarEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarEnergy(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 AsBaseUnit() - { - switch(Unit) - { - case MolarEnergyUnit.JoulePerMole: return _value; - case MolarEnergyUnit.KilojoulePerMole: return (_value) * 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarEnergyUnit.JoulePerMole: return baseUnitValue; - case MolarEnergyUnit.KilojoulePerMole: return (baseUnitValue) / 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MolarEnergy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarEnergy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEnergyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MolarEnergyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MolarEnergy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarEnergy result) - { - result = default(MolarEnergy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MolarEnergyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MolarEnergyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MolarEnergyUnit unit) - { - unit = MolarEnergyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MolarEnergyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MolarEnergy - /// - public static MolarEnergy MaxValue => new MolarEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MolarEnergy - /// - public static MolarEnergy MinValue => new MolarEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MolarEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs b/Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs deleted file mode 100644 index dfc6fdcff9..0000000000 --- a/Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MolarEntropy : IQuantity -#else - public partial struct MolarEntropy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarEntropyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MolarEntropy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MolarEntropy(double numericValue, MolarEntropyUnit unit) - { - if(unit == MolarEntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MolarEntropy; - - /// - /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. - /// - public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MolarEntropy quantity. - /// - public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); - - /// - /// Get MolarEntropy in JoulesPerMoleKelvin. - /// - public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); - - /// - /// Get MolarEntropy in KilojoulesPerMoleKelvin. - /// - public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); - - /// - /// Get MolarEntropy in MegajoulesPerMoleKelvin. - /// - public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. - /// - public static MolarEntropy Zero => new MolarEntropy(0, BaseUnit); - - /// - /// Get MolarEntropy from JoulesPerMoleKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromJoulesPerMoleKelvin(double joulespermolekelvin) -#else - public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) -#endif - { - double value = (double) joulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); - } - - /// - /// Get MolarEntropy from KilojoulesPerMoleKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromKilojoulesPerMoleKelvin(double kilojoulespermolekelvin) -#else - public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) -#endif - { - double value = (double) kilojoulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); - } - - /// - /// Get MolarEntropy from MegajoulesPerMoleKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromMegajoulesPerMoleKelvin(double megajoulespermolekelvin) -#else - public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) -#endif - { - double value = (double) megajoulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarEntropy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) -#else - public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) -#endif - { - return new MolarEntropy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarEntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MolarEntropy)) throw new ArgumentException("Expected type MolarEntropy.", nameof(obj)); - - return CompareTo((MolarEntropy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MolarEntropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MolarEntropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEntropy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEntropyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarEntropy to another MolarEntropy with the unit representation . - /// - /// A MolarEntropy with the specified unit. - public MolarEntropy ToUnit(MolarEntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarEntropy(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 AsBaseUnit() - { - switch(Unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return _value; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (_value) * 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarEntropyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return baseUnitValue; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (baseUnitValue) / 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MolarEntropy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarEntropy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEntropyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MolarEntropyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MolarEntropy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarEntropy result) - { - result = default(MolarEntropy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MolarEntropyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MolarEntropyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MolarEntropyUnit unit) - { - unit = MolarEntropyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MolarEntropyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarEntropyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MolarEntropy - /// - public static MolarEntropy MaxValue => new MolarEntropy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MolarEntropy - /// - public static MolarEntropy MinValue => new MolarEntropy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MolarEntropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MolarMass.Common.g.cs b/Common/GeneratedCode/Quantities/MolarMass.Common.g.cs deleted file mode 100644 index b4522ad436..0000000000 --- a/Common/GeneratedCode/Quantities/MolarMass.Common.g.cs +++ /dev/null @@ -1,779 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MolarMass : IQuantity -#else - public partial struct MolarMass : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarMassUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MolarMass() - { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - MolarMass(double numericValue, MolarMassUnit unit) - { - if(unit == MolarMassUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MolarMass; - - /// - /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. - /// - public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MolarMass quantity. - /// - public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); - - /// - /// Get MolarMass in CentigramsPerMole. - /// - public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); - - /// - /// Get MolarMass in DecagramsPerMole. - /// - public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); - - /// - /// Get MolarMass in DecigramsPerMole. - /// - public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); - - /// - /// Get MolarMass in GramsPerMole. - /// - public double GramsPerMole => As(MolarMassUnit.GramPerMole); - - /// - /// Get MolarMass in HectogramsPerMole. - /// - public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); - - /// - /// Get MolarMass in KilogramsPerMole. - /// - public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); - - /// - /// Get MolarMass in KilopoundsPerMole. - /// - public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); - - /// - /// Get MolarMass in MegapoundsPerMole. - /// - public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); - - /// - /// Get MolarMass in MicrogramsPerMole. - /// - public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); - - /// - /// Get MolarMass in MilligramsPerMole. - /// - public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); - - /// - /// Get MolarMass in NanogramsPerMole. - /// - public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); - - /// - /// Get MolarMass in PoundsPerMole. - /// - public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. - /// - public static MolarMass Zero => new MolarMass(0, BaseUnit); - - /// - /// Get MolarMass from CentigramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromCentigramsPerMole(double centigramspermole) -#else - public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) -#endif - { - double value = (double) centigramspermole; - return new MolarMass(value, MolarMassUnit.CentigramPerMole); - } - - /// - /// Get MolarMass from DecagramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromDecagramsPerMole(double decagramspermole) -#else - public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) -#endif - { - double value = (double) decagramspermole; - return new MolarMass(value, MolarMassUnit.DecagramPerMole); - } - - /// - /// Get MolarMass from DecigramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromDecigramsPerMole(double decigramspermole) -#else - public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) -#endif - { - double value = (double) decigramspermole; - return new MolarMass(value, MolarMassUnit.DecigramPerMole); - } - - /// - /// Get MolarMass from GramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromGramsPerMole(double gramspermole) -#else - public static MolarMass FromGramsPerMole(QuantityValue gramspermole) -#endif - { - double value = (double) gramspermole; - return new MolarMass(value, MolarMassUnit.GramPerMole); - } - - /// - /// Get MolarMass from HectogramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromHectogramsPerMole(double hectogramspermole) -#else - public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) -#endif - { - double value = (double) hectogramspermole; - return new MolarMass(value, MolarMassUnit.HectogramPerMole); - } - - /// - /// Get MolarMass from KilogramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromKilogramsPerMole(double kilogramspermole) -#else - public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) -#endif - { - double value = (double) kilogramspermole; - return new MolarMass(value, MolarMassUnit.KilogramPerMole); - } - - /// - /// Get MolarMass from KilopoundsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) -#else - public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) -#endif - { - double value = (double) kilopoundspermole; - return new MolarMass(value, MolarMassUnit.KilopoundPerMole); - } - - /// - /// Get MolarMass from MegapoundsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMegapoundsPerMole(double megapoundspermole) -#else - public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) -#endif - { - double value = (double) megapoundspermole; - return new MolarMass(value, MolarMassUnit.MegapoundPerMole); - } - - /// - /// Get MolarMass from MicrogramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMicrogramsPerMole(double microgramspermole) -#else - public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) -#endif - { - double value = (double) microgramspermole; - return new MolarMass(value, MolarMassUnit.MicrogramPerMole); - } - - /// - /// Get MolarMass from MilligramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMilligramsPerMole(double milligramspermole) -#else - public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) -#endif - { - double value = (double) milligramspermole; - return new MolarMass(value, MolarMassUnit.MilligramPerMole); - } - - /// - /// Get MolarMass from NanogramsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromNanogramsPerMole(double nanogramspermole) -#else - public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) -#endif - { - double value = (double) nanogramspermole; - return new MolarMass(value, MolarMassUnit.NanogramPerMole); - } - - /// - /// Get MolarMass from PoundsPerMole. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromPoundsPerMole(double poundspermole) -#else - public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) -#endif - { - double value = (double) poundspermole; - return new MolarMass(value, MolarMassUnit.PoundPerMole); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarMass unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarMass From(double value, MolarMassUnit fromUnit) -#else - public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) -#endif - { - return new MolarMass((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarMassUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MolarMass)) throw new ArgumentException("Expected type MolarMass.", nameof(obj)); - - return CompareTo((MolarMass)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MolarMass other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MolarMass within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarMass. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarMassUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarMass to another MolarMass with the unit representation . - /// - /// A MolarMass with the specified unit. - public MolarMass ToUnit(MolarMassUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarMass(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 AsBaseUnit() - { - switch(Unit) - { - case MolarMassUnit.CentigramPerMole: return (_value/1e3) * 1e-2d; - case MolarMassUnit.DecagramPerMole: return (_value/1e3) * 1e1d; - case MolarMassUnit.DecigramPerMole: return (_value/1e3) * 1e-1d; - case MolarMassUnit.GramPerMole: return _value/1e3; - case MolarMassUnit.HectogramPerMole: return (_value/1e3) * 1e2d; - case MolarMassUnit.KilogramPerMole: return (_value/1e3) * 1e3d; - case MolarMassUnit.KilopoundPerMole: return (_value*0.45359237) * 1e3d; - case MolarMassUnit.MegapoundPerMole: return (_value*0.45359237) * 1e6d; - case MolarMassUnit.MicrogramPerMole: return (_value/1e3) * 1e-6d; - case MolarMassUnit.MilligramPerMole: return (_value/1e3) * 1e-3d; - case MolarMassUnit.NanogramPerMole: return (_value/1e3) * 1e-9d; - case MolarMassUnit.PoundPerMole: return _value*0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarMassUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarMassUnit.CentigramPerMole: return (baseUnitValue*1e3) / 1e-2d; - case MolarMassUnit.DecagramPerMole: return (baseUnitValue*1e3) / 1e1d; - case MolarMassUnit.DecigramPerMole: return (baseUnitValue*1e3) / 1e-1d; - case MolarMassUnit.GramPerMole: return baseUnitValue*1e3; - case MolarMassUnit.HectogramPerMole: return (baseUnitValue*1e3) / 1e2d; - case MolarMassUnit.KilogramPerMole: return (baseUnitValue*1e3) / 1e3d; - case MolarMassUnit.KilopoundPerMole: return (baseUnitValue/0.45359237) / 1e3d; - case MolarMassUnit.MegapoundPerMole: return (baseUnitValue/0.45359237) / 1e6d; - case MolarMassUnit.MicrogramPerMole: return (baseUnitValue*1e3) / 1e-6d; - case MolarMassUnit.MilligramPerMole: return (baseUnitValue*1e3) / 1e-3d; - case MolarMassUnit.NanogramPerMole: return (baseUnitValue*1e3) / 1e-9d; - case MolarMassUnit.PoundPerMole: return baseUnitValue/0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 MolarMass Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarMass result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarMassUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MolarMassUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static MolarMass ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarMass result) - { - result = default(MolarMass); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MolarMassUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MolarMassUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarMassUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MolarMassUnit unit) - { - unit = MolarMassUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MolarMassUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarMassUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MolarMass - /// - public static MolarMass MaxValue => new MolarMass(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MolarMass - /// - public static MolarMass MinValue => new MolarMass(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MolarMass.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarMass.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Molarity.Common.g.cs b/Common/GeneratedCode/Quantities/Molarity.Common.g.cs deleted file mode 100644 index a433111a73..0000000000 --- a/Common/GeneratedCode/Quantities/Molarity.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Molarity : IQuantity -#else - public partial struct Molarity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Molarity() - { - BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Molarity(double numericValue, MolarityUnit unit) - { - if(unit == MolarityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Molarity; - - /// - /// The base unit of Molarity, which is MolesPerCubicMeter. All conversions go via this value. - /// - public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Molarity quantity. - /// - public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); - - /// - /// Get Molarity in CentimolesPerLiter. - /// - public double CentimolesPerLiter => As(MolarityUnit.CentimolesPerLiter); - - /// - /// Get Molarity in DecimolesPerLiter. - /// - public double DecimolesPerLiter => As(MolarityUnit.DecimolesPerLiter); - - /// - /// Get Molarity in MicromolesPerLiter. - /// - public double MicromolesPerLiter => As(MolarityUnit.MicromolesPerLiter); - - /// - /// Get Molarity in MillimolesPerLiter. - /// - public double MillimolesPerLiter => As(MolarityUnit.MillimolesPerLiter); - - /// - /// Get Molarity in MolesPerCubicMeter. - /// - public double MolesPerCubicMeter => As(MolarityUnit.MolesPerCubicMeter); - - /// - /// Get Molarity in MolesPerLiter. - /// - public double MolesPerLiter => As(MolarityUnit.MolesPerLiter); - - /// - /// Get Molarity in NanomolesPerLiter. - /// - public double NanomolesPerLiter => As(MolarityUnit.NanomolesPerLiter); - - /// - /// Get Molarity in PicomolesPerLiter. - /// - public double PicomolesPerLiter => As(MolarityUnit.PicomolesPerLiter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. - /// - public static Molarity Zero => new Molarity(0, BaseUnit); - - /// - /// Get Molarity from CentimolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromCentimolesPerLiter(double centimolesperliter) -#else - public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) -#endif - { - double value = (double) centimolesperliter; - return new Molarity(value, MolarityUnit.CentimolesPerLiter); - } - - /// - /// Get Molarity from DecimolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromDecimolesPerLiter(double decimolesperliter) -#else - public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) -#endif - { - double value = (double) decimolesperliter; - return new Molarity(value, MolarityUnit.DecimolesPerLiter); - } - - /// - /// Get Molarity from MicromolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMicromolesPerLiter(double micromolesperliter) -#else - public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) -#endif - { - double value = (double) micromolesperliter; - return new Molarity(value, MolarityUnit.MicromolesPerLiter); - } - - /// - /// Get Molarity from MillimolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMillimolesPerLiter(double millimolesperliter) -#else - public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) -#endif - { - double value = (double) millimolesperliter; - return new Molarity(value, MolarityUnit.MillimolesPerLiter); - } - - /// - /// Get Molarity from MolesPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMolesPerCubicMeter(double molespercubicmeter) -#else - public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) -#endif - { - double value = (double) molespercubicmeter; - return new Molarity(value, MolarityUnit.MolesPerCubicMeter); - } - - /// - /// Get Molarity from MolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMolesPerLiter(double molesperliter) -#else - public static Molarity FromMolesPerLiter(QuantityValue molesperliter) -#endif - { - double value = (double) molesperliter; - return new Molarity(value, MolarityUnit.MolesPerLiter); - } - - /// - /// Get Molarity from NanomolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromNanomolesPerLiter(double nanomolesperliter) -#else - public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) -#endif - { - double value = (double) nanomolesperliter; - return new Molarity(value, MolarityUnit.NanomolesPerLiter); - } - - /// - /// Get Molarity from PicomolesPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromPicomolesPerLiter(double picomolesperliter) -#else - public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) -#endif - { - double value = (double) picomolesperliter; - return new Molarity(value, MolarityUnit.PicomolesPerLiter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Molarity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Molarity From(double value, MolarityUnit fromUnit) -#else - public static Molarity From(QuantityValue value, MolarityUnit fromUnit) -#endif - { - return new Molarity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Molarity)) throw new ArgumentException("Expected type Molarity.", nameof(obj)); - - return CompareTo((Molarity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Molarity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Molarity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Molarity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Molarity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Molarity to another Molarity with the unit representation . - /// - /// A Molarity with the specified unit. - public Molarity ToUnit(MolarityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Molarity(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 AsBaseUnit() - { - switch(Unit) - { - case MolarityUnit.CentimolesPerLiter: return (_value/1e-3) * 1e-2d; - case MolarityUnit.DecimolesPerLiter: return (_value/1e-3) * 1e-1d; - case MolarityUnit.MicromolesPerLiter: return (_value/1e-3) * 1e-6d; - case MolarityUnit.MillimolesPerLiter: return (_value/1e-3) * 1e-3d; - case MolarityUnit.MolesPerCubicMeter: return _value; - case MolarityUnit.MolesPerLiter: return _value/1e-3; - case MolarityUnit.NanomolesPerLiter: return (_value/1e-3) * 1e-9d; - case MolarityUnit.PicomolesPerLiter: return (_value/1e-3) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarityUnit.CentimolesPerLiter: return (baseUnitValue*1e-3) / 1e-2d; - case MolarityUnit.DecimolesPerLiter: return (baseUnitValue*1e-3) / 1e-1d; - case MolarityUnit.MicromolesPerLiter: return (baseUnitValue*1e-3) / 1e-6d; - case MolarityUnit.MillimolesPerLiter: return (baseUnitValue*1e-3) / 1e-3d; - case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; - case MolarityUnit.MolesPerLiter: return baseUnitValue*1e-3; - case MolarityUnit.NanomolesPerLiter: return (baseUnitValue*1e-3) / 1e-9d; - case MolarityUnit.PicomolesPerLiter: return (baseUnitValue*1e-3) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Molarity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Molarity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out MolarityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Molarity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Molarity result) - { - result = default(Molarity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static MolarityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == MolarityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out MolarityUnit unit) - { - unit = MolarityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == MolarityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Molarity - /// - public static Molarity MaxValue => new Molarity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Molarity - /// - public static Molarity MinValue => new Molarity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Molarity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Molarity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Permeability.Common.g.cs b/Common/GeneratedCode/Quantities/Permeability.Common.g.cs deleted file mode 100644 index b04f222029..0000000000 --- a/Common/GeneratedCode/Quantities/Permeability.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Permeability : IQuantity -#else - public partial struct Permeability : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PermeabilityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Permeability() - { - BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Permeability(double numericValue, PermeabilityUnit unit) - { - if(unit == PermeabilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Permeability; - - /// - /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. - /// - public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Permeability quantity. - /// - public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); - - /// - /// Get Permeability in HenriesPerMeter. - /// - public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. - /// - public static Permeability Zero => new Permeability(0, BaseUnit); - - /// - /// Get Permeability from HenriesPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Permeability FromHenriesPerMeter(double henriespermeter) -#else - public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) -#endif - { - double value = (double) henriespermeter; - return new Permeability(value, PermeabilityUnit.HenryPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Permeability unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Permeability From(double value, PermeabilityUnit fromUnit) -#else - public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) -#endif - { - return new Permeability((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PermeabilityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Permeability)) throw new ArgumentException("Expected type Permeability.", nameof(obj)); - - return CompareTo((Permeability)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Permeability other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Permeability within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Permeability other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permeability. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermeabilityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Permeability to another Permeability with the unit representation . - /// - /// A Permeability with the specified unit. - public Permeability ToUnit(PermeabilityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Permeability(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 AsBaseUnit() - { - switch(Unit) - { - case PermeabilityUnit.HenryPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PermeabilityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PermeabilityUnit.HenryPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Permeability Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Permeability result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermeabilityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PermeabilityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Permeability ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permeability result) - { - result = default(Permeability); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PermeabilityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PermeabilityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermeabilityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PermeabilityUnit unit) - { - unit = PermeabilityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PermeabilityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PermeabilityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Permeability - /// - public static Permeability MaxValue => new Permeability(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Permeability - /// - public static Permeability MinValue => new Permeability(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Permeability.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Permeability.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Permittivity.Common.g.cs b/Common/GeneratedCode/Quantities/Permittivity.Common.g.cs deleted file mode 100644 index 3fb2bd490f..0000000000 --- a/Common/GeneratedCode/Quantities/Permittivity.Common.g.cs +++ /dev/null @@ -1,537 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Permittivity : IQuantity -#else - public partial struct Permittivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PermittivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Permittivity() - { - BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Permittivity(double numericValue, PermittivityUnit unit) - { - if(unit == PermittivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Permittivity; - - /// - /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. - /// - public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Permittivity quantity. - /// - public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); - - /// - /// Get Permittivity in FaradsPerMeter. - /// - public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. - /// - public static Permittivity Zero => new Permittivity(0, BaseUnit); - - /// - /// Get Permittivity from FaradsPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Permittivity FromFaradsPerMeter(double faradspermeter) -#else - public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) -#endif - { - double value = (double) faradspermeter; - return new Permittivity(value, PermittivityUnit.FaradPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Permittivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Permittivity From(double value, PermittivityUnit fromUnit) -#else - public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) -#endif - { - return new Permittivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PermittivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Permittivity)) throw new ArgumentException("Expected type Permittivity.", nameof(obj)); - - return CompareTo((Permittivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Permittivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Permittivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Permittivity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permittivity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermittivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Permittivity to another Permittivity with the unit representation . - /// - /// A Permittivity with the specified unit. - public Permittivity ToUnit(PermittivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Permittivity(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 AsBaseUnit() - { - switch(Unit) - { - case PermittivityUnit.FaradPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PermittivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PermittivityUnit.FaradPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Permittivity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Permittivity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermittivityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PermittivityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Permittivity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permittivity result) - { - result = default(Permittivity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PermittivityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PermittivityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermittivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PermittivityUnit unit) - { - unit = PermittivityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PermittivityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PermittivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Permittivity - /// - public static Permittivity MaxValue => new Permittivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Permittivity - /// - public static Permittivity MinValue => new Permittivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Permittivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Permittivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Power.Common.g.cs b/Common/GeneratedCode/Quantities/Power.Common.g.cs deleted file mode 100644 index 03c8a5e79e..0000000000 --- a/Common/GeneratedCode/Quantities/Power.Common.g.cs +++ /dev/null @@ -1,955 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Power : IQuantity -#else - public partial struct Power : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Power() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Power(decimal numericValue, PowerUnit unit) - { - if(unit == PowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = numericValue; - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Power; - - /// - /// The base unit of Power, which is Watt. All conversions go via this value. - /// - public static PowerUnit BaseUnit => PowerUnit.Watt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Power quantity. - /// - public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); - - /// - /// Get Power in BoilerHorsepower. - /// - public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); - - /// - /// Get Power in BritishThermalUnitsPerHour. - /// - public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); - - /// - /// Get Power in Decawatts. - /// - public double Decawatts => As(PowerUnit.Decawatt); - - /// - /// Get Power in Deciwatts. - /// - public double Deciwatts => As(PowerUnit.Deciwatt); - - /// - /// Get Power in ElectricalHorsepower. - /// - public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); - - /// - /// Get Power in Femtowatts. - /// - public double Femtowatts => As(PowerUnit.Femtowatt); - - /// - /// Get Power in Gigawatts. - /// - public double Gigawatts => As(PowerUnit.Gigawatt); - - /// - /// Get Power in HydraulicHorsepower. - /// - public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); - - /// - /// Get Power in KilobritishThermalUnitsPerHour. - /// - public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); - - /// - /// Get Power in Kilowatts. - /// - public double Kilowatts => As(PowerUnit.Kilowatt); - - /// - /// Get Power in MechanicalHorsepower. - /// - public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); - - /// - /// Get Power in Megawatts. - /// - public double Megawatts => As(PowerUnit.Megawatt); - - /// - /// Get Power in MetricHorsepower. - /// - public double MetricHorsepower => As(PowerUnit.MetricHorsepower); - - /// - /// Get Power in Microwatts. - /// - public double Microwatts => As(PowerUnit.Microwatt); - - /// - /// Get Power in Milliwatts. - /// - public double Milliwatts => As(PowerUnit.Milliwatt); - - /// - /// Get Power in Nanowatts. - /// - public double Nanowatts => As(PowerUnit.Nanowatt); - - /// - /// Get Power in Petawatts. - /// - public double Petawatts => As(PowerUnit.Petawatt); - - /// - /// Get Power in Picowatts. - /// - public double Picowatts => As(PowerUnit.Picowatt); - - /// - /// Get Power in Terawatts. - /// - public double Terawatts => As(PowerUnit.Terawatt); - - /// - /// Get Power in Watts. - /// - public double Watts => As(PowerUnit.Watt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Watt. - /// - public static Power Zero => new Power(0, BaseUnit); - - /// - /// Get Power from BoilerHorsepower. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromBoilerHorsepower(double boilerhorsepower) -#else - public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) -#endif - { - decimal value = (decimal) boilerhorsepower; - return new Power(value, PowerUnit.BoilerHorsepower); - } - - /// - /// Get Power from BritishThermalUnitsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromBritishThermalUnitsPerHour(double britishthermalunitsperhour) -#else - public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) -#endif - { - decimal value = (decimal) britishthermalunitsperhour; - return new Power(value, PowerUnit.BritishThermalUnitPerHour); - } - - /// - /// Get Power from Decawatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromDecawatts(double decawatts) -#else - public static Power FromDecawatts(QuantityValue decawatts) -#endif - { - decimal value = (decimal) decawatts; - return new Power(value, PowerUnit.Decawatt); - } - - /// - /// Get Power from Deciwatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromDeciwatts(double deciwatts) -#else - public static Power FromDeciwatts(QuantityValue deciwatts) -#endif - { - decimal value = (decimal) deciwatts; - return new Power(value, PowerUnit.Deciwatt); - } - - /// - /// Get Power from ElectricalHorsepower. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromElectricalHorsepower(double electricalhorsepower) -#else - public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) -#endif - { - decimal value = (decimal) electricalhorsepower; - return new Power(value, PowerUnit.ElectricalHorsepower); - } - - /// - /// Get Power from Femtowatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromFemtowatts(double femtowatts) -#else - public static Power FromFemtowatts(QuantityValue femtowatts) -#endif - { - decimal value = (decimal) femtowatts; - return new Power(value, PowerUnit.Femtowatt); - } - - /// - /// Get Power from Gigawatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromGigawatts(double gigawatts) -#else - public static Power FromGigawatts(QuantityValue gigawatts) -#endif - { - decimal value = (decimal) gigawatts; - return new Power(value, PowerUnit.Gigawatt); - } - - /// - /// Get Power from HydraulicHorsepower. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromHydraulicHorsepower(double hydraulichorsepower) -#else - public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) -#endif - { - decimal value = (decimal) hydraulichorsepower; - return new Power(value, PowerUnit.HydraulicHorsepower); - } - - /// - /// Get Power from KilobritishThermalUnitsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilobritishThermalUnitsPerHour(double kilobritishthermalunitsperhour) -#else - public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) -#endif - { - decimal value = (decimal) kilobritishthermalunitsperhour; - return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); - } - - /// - /// Get Power from Kilowatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilowatts(double kilowatts) -#else - public static Power FromKilowatts(QuantityValue kilowatts) -#endif - { - decimal value = (decimal) kilowatts; - return new Power(value, PowerUnit.Kilowatt); - } - - /// - /// Get Power from MechanicalHorsepower. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMechanicalHorsepower(double mechanicalhorsepower) -#else - public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) -#endif - { - decimal value = (decimal) mechanicalhorsepower; - return new Power(value, PowerUnit.MechanicalHorsepower); - } - - /// - /// Get Power from Megawatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMegawatts(double megawatts) -#else - public static Power FromMegawatts(QuantityValue megawatts) -#endif - { - decimal value = (decimal) megawatts; - return new Power(value, PowerUnit.Megawatt); - } - - /// - /// Get Power from MetricHorsepower. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMetricHorsepower(double metrichorsepower) -#else - public static Power FromMetricHorsepower(QuantityValue metrichorsepower) -#endif - { - decimal value = (decimal) metrichorsepower; - return new Power(value, PowerUnit.MetricHorsepower); - } - - /// - /// Get Power from Microwatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMicrowatts(double microwatts) -#else - public static Power FromMicrowatts(QuantityValue microwatts) -#endif - { - decimal value = (decimal) microwatts; - return new Power(value, PowerUnit.Microwatt); - } - - /// - /// Get Power from Milliwatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMilliwatts(double milliwatts) -#else - public static Power FromMilliwatts(QuantityValue milliwatts) -#endif - { - decimal value = (decimal) milliwatts; - return new Power(value, PowerUnit.Milliwatt); - } - - /// - /// Get Power from Nanowatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromNanowatts(double nanowatts) -#else - public static Power FromNanowatts(QuantityValue nanowatts) -#endif - { - decimal value = (decimal) nanowatts; - return new Power(value, PowerUnit.Nanowatt); - } - - /// - /// Get Power from Petawatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromPetawatts(double petawatts) -#else - public static Power FromPetawatts(QuantityValue petawatts) -#endif - { - decimal value = (decimal) petawatts; - return new Power(value, PowerUnit.Petawatt); - } - - /// - /// Get Power from Picowatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromPicowatts(double picowatts) -#else - public static Power FromPicowatts(QuantityValue picowatts) -#endif - { - decimal value = (decimal) picowatts; - return new Power(value, PowerUnit.Picowatt); - } - - /// - /// Get Power from Terawatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromTerawatts(double terawatts) -#else - public static Power FromTerawatts(QuantityValue terawatts) -#endif - { - decimal value = (decimal) terawatts; - return new Power(value, PowerUnit.Terawatt); - } - - /// - /// Get Power from Watts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromWatts(double watts) -#else - public static Power FromWatts(QuantityValue watts) -#endif - { - decimal value = (decimal) watts; - return new Power(value, PowerUnit.Watt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Power unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Power From(double value, PowerUnit fromUnit) -#else - public static Power From(QuantityValue value, PowerUnit fromUnit) -#endif - { - return new Power((decimal)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Power)) throw new ArgumentException("Expected type Power.", nameof(obj)); - - return CompareTo((Power)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Power other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Power within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Power other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Power. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Power to another Power with the unit representation . - /// - /// A Power with the specified unit. - public Power ToUnit(PowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Power(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 decimal AsBaseUnit() - { - switch(Unit) - { - case PowerUnit.BoilerHorsepower: return _value*9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return _value*0.293071m; - case PowerUnit.Decawatt: return (_value) * 1e1m; - case PowerUnit.Deciwatt: return (_value) * 1e-1m; - case PowerUnit.ElectricalHorsepower: return _value*746m; - case PowerUnit.Femtowatt: return (_value) * 1e-15m; - case PowerUnit.Gigawatt: return (_value) * 1e9m; - case PowerUnit.HydraulicHorsepower: return _value*745.69988145m; - case PowerUnit.KilobritishThermalUnitPerHour: return (_value*0.293071m) * 1e3m; - case PowerUnit.Kilowatt: return (_value) * 1e3m; - case PowerUnit.MechanicalHorsepower: return _value*745.69m; - case PowerUnit.Megawatt: return (_value) * 1e6m; - case PowerUnit.MetricHorsepower: return _value*735.49875m; - case PowerUnit.Microwatt: return (_value) * 1e-6m; - case PowerUnit.Milliwatt: return (_value) * 1e-3m; - case PowerUnit.Nanowatt: return (_value) * 1e-9m; - case PowerUnit.Petawatt: return (_value) * 1e15m; - case PowerUnit.Picowatt: return (_value) * 1e-12m; - case PowerUnit.Terawatt: return (_value) * 1e12m; - case PowerUnit.Watt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(PowerUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerUnit.BoilerHorsepower: return baseUnitValue/9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return baseUnitValue/0.293071m; - case PowerUnit.Decawatt: return (baseUnitValue) / 1e1m; - case PowerUnit.Deciwatt: return (baseUnitValue) / 1e-1m; - case PowerUnit.ElectricalHorsepower: return baseUnitValue/746m; - case PowerUnit.Femtowatt: return (baseUnitValue) / 1e-15m; - case PowerUnit.Gigawatt: return (baseUnitValue) / 1e9m; - case PowerUnit.HydraulicHorsepower: return baseUnitValue/745.69988145m; - case PowerUnit.KilobritishThermalUnitPerHour: return (baseUnitValue/0.293071m) / 1e3m; - case PowerUnit.Kilowatt: return (baseUnitValue) / 1e3m; - case PowerUnit.MechanicalHorsepower: return baseUnitValue/745.69m; - case PowerUnit.Megawatt: return (baseUnitValue) / 1e6m; - case PowerUnit.MetricHorsepower: return baseUnitValue/735.49875m; - case PowerUnit.Microwatt: return (baseUnitValue) / 1e-6m; - case PowerUnit.Milliwatt: return (baseUnitValue) / 1e-3m; - case PowerUnit.Nanowatt: return (baseUnitValue) / 1e-9m; - case PowerUnit.Petawatt: return (baseUnitValue) / 1e15m; - case PowerUnit.Picowatt: return (baseUnitValue) / 1e-12m; - case PowerUnit.Terawatt: return (baseUnitValue) / 1e12m; - case PowerUnit.Watt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Power Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Power result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PowerUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Power ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Power result) - { - result = default(Power); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PowerUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PowerUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PowerUnit unit) - { - unit = PowerUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PowerUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PowerUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Power - /// - public static Power MaxValue => new Power(decimal.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Power - /// - public static Power MinValue => new Power(decimal.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Power.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Power.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs b/Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs deleted file mode 100644 index 8ec46a9658..0000000000 --- a/Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs +++ /dev/null @@ -1,1483 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The amount of power in a volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class PowerDensity : IQuantity -#else - public partial struct PowerDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static PowerDensity() - { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - PowerDensity(double numericValue, PowerDensityUnit unit) - { - if(unit == PowerDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.PowerDensity; - - /// - /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. - /// - public static PowerDensityUnit BaseUnit => PowerDensityUnit.WattPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the PowerDensity quantity. - /// - public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); - - /// - /// Get PowerDensity in DecawattsPerCubicFoot. - /// - public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); - - /// - /// Get PowerDensity in DecawattsPerCubicInch. - /// - public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); - - /// - /// Get PowerDensity in DecawattsPerCubicMeter. - /// - public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); - - /// - /// Get PowerDensity in DecawattsPerLiter. - /// - public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); - - /// - /// Get PowerDensity in DeciwattsPerCubicFoot. - /// - public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); - - /// - /// Get PowerDensity in DeciwattsPerCubicInch. - /// - public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); - - /// - /// Get PowerDensity in DeciwattsPerCubicMeter. - /// - public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); - - /// - /// Get PowerDensity in DeciwattsPerLiter. - /// - public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); - - /// - /// Get PowerDensity in GigawattsPerCubicFoot. - /// - public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); - - /// - /// Get PowerDensity in GigawattsPerCubicInch. - /// - public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); - - /// - /// Get PowerDensity in GigawattsPerCubicMeter. - /// - public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); - - /// - /// Get PowerDensity in GigawattsPerLiter. - /// - public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); - - /// - /// Get PowerDensity in KilowattsPerCubicFoot. - /// - public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); - - /// - /// Get PowerDensity in KilowattsPerCubicInch. - /// - public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); - - /// - /// Get PowerDensity in KilowattsPerCubicMeter. - /// - public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); - - /// - /// Get PowerDensity in KilowattsPerLiter. - /// - public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); - - /// - /// Get PowerDensity in MegawattsPerCubicFoot. - /// - public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); - - /// - /// Get PowerDensity in MegawattsPerCubicInch. - /// - public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); - - /// - /// Get PowerDensity in MegawattsPerCubicMeter. - /// - public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); - - /// - /// Get PowerDensity in MegawattsPerLiter. - /// - public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); - - /// - /// Get PowerDensity in MicrowattsPerCubicFoot. - /// - public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); - - /// - /// Get PowerDensity in MicrowattsPerCubicInch. - /// - public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); - - /// - /// Get PowerDensity in MicrowattsPerCubicMeter. - /// - public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); - - /// - /// Get PowerDensity in MicrowattsPerLiter. - /// - public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); - - /// - /// Get PowerDensity in MilliwattsPerCubicFoot. - /// - public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); - - /// - /// Get PowerDensity in MilliwattsPerCubicInch. - /// - public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); - - /// - /// Get PowerDensity in MilliwattsPerCubicMeter. - /// - public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); - - /// - /// Get PowerDensity in MilliwattsPerLiter. - /// - public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); - - /// - /// Get PowerDensity in NanowattsPerCubicFoot. - /// - public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); - - /// - /// Get PowerDensity in NanowattsPerCubicInch. - /// - public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); - - /// - /// Get PowerDensity in NanowattsPerCubicMeter. - /// - public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); - - /// - /// Get PowerDensity in NanowattsPerLiter. - /// - public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); - - /// - /// Get PowerDensity in PicowattsPerCubicFoot. - /// - public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); - - /// - /// Get PowerDensity in PicowattsPerCubicInch. - /// - public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); - - /// - /// Get PowerDensity in PicowattsPerCubicMeter. - /// - public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); - - /// - /// Get PowerDensity in PicowattsPerLiter. - /// - public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); - - /// - /// Get PowerDensity in TerawattsPerCubicFoot. - /// - public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); - - /// - /// Get PowerDensity in TerawattsPerCubicInch. - /// - public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); - - /// - /// Get PowerDensity in TerawattsPerCubicMeter. - /// - public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); - - /// - /// Get PowerDensity in TerawattsPerLiter. - /// - public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); - - /// - /// Get PowerDensity in WattsPerCubicFoot. - /// - public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); - - /// - /// Get PowerDensity in WattsPerCubicInch. - /// - public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); - - /// - /// Get PowerDensity in WattsPerCubicMeter. - /// - public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); - - /// - /// Get PowerDensity in WattsPerLiter. - /// - public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. - /// - public static PowerDensity Zero => new PowerDensity(0, BaseUnit); - - /// - /// Get PowerDensity from DecawattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicFoot(double decawattspercubicfoot) -#else - public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattspercubicfoot) -#endif - { - double value = (double) decawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); - } - - /// - /// Get PowerDensity from DecawattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicInch(double decawattspercubicinch) -#else - public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattspercubicinch) -#endif - { - double value = (double) decawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); - } - - /// - /// Get PowerDensity from DecawattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicMeter(double decawattspercubicmeter) -#else - public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattspercubicmeter) -#endif - { - double value = (double) decawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); - } - - /// - /// Get PowerDensity from DecawattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerLiter(double decawattsperliter) -#else - public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter) -#endif - { - double value = (double) decawattsperliter; - return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); - } - - /// - /// Get PowerDensity from DeciwattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicFoot(double deciwattspercubicfoot) -#else - public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattspercubicfoot) -#endif - { - double value = (double) deciwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); - } - - /// - /// Get PowerDensity from DeciwattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicInch(double deciwattspercubicinch) -#else - public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattspercubicinch) -#endif - { - double value = (double) deciwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); - } - - /// - /// Get PowerDensity from DeciwattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicMeter(double deciwattspercubicmeter) -#else - public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattspercubicmeter) -#endif - { - double value = (double) deciwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); - } - - /// - /// Get PowerDensity from DeciwattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerLiter(double deciwattsperliter) -#else - public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter) -#endif - { - double value = (double) deciwattsperliter; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); - } - - /// - /// Get PowerDensity from GigawattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicFoot(double gigawattspercubicfoot) -#else - public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattspercubicfoot) -#endif - { - double value = (double) gigawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); - } - - /// - /// Get PowerDensity from GigawattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicInch(double gigawattspercubicinch) -#else - public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattspercubicinch) -#endif - { - double value = (double) gigawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); - } - - /// - /// Get PowerDensity from GigawattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicMeter(double gigawattspercubicmeter) -#else - public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattspercubicmeter) -#endif - { - double value = (double) gigawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); - } - - /// - /// Get PowerDensity from GigawattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerLiter(double gigawattsperliter) -#else - public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter) -#endif - { - double value = (double) gigawattsperliter; - return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); - } - - /// - /// Get PowerDensity from KilowattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicFoot(double kilowattspercubicfoot) -#else - public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattspercubicfoot) -#endif - { - double value = (double) kilowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); - } - - /// - /// Get PowerDensity from KilowattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicInch(double kilowattspercubicinch) -#else - public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattspercubicinch) -#endif - { - double value = (double) kilowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); - } - - /// - /// Get PowerDensity from KilowattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicMeter(double kilowattspercubicmeter) -#else - public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattspercubicmeter) -#endif - { - double value = (double) kilowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); - } - - /// - /// Get PowerDensity from KilowattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerLiter(double kilowattsperliter) -#else - public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter) -#endif - { - double value = (double) kilowattsperliter; - return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); - } - - /// - /// Get PowerDensity from MegawattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicFoot(double megawattspercubicfoot) -#else - public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattspercubicfoot) -#endif - { - double value = (double) megawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); - } - - /// - /// Get PowerDensity from MegawattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicInch(double megawattspercubicinch) -#else - public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattspercubicinch) -#endif - { - double value = (double) megawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); - } - - /// - /// Get PowerDensity from MegawattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicMeter(double megawattspercubicmeter) -#else - public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattspercubicmeter) -#endif - { - double value = (double) megawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); - } - - /// - /// Get PowerDensity from MegawattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerLiter(double megawattsperliter) -#else - public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter) -#endif - { - double value = (double) megawattsperliter; - return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); - } - - /// - /// Get PowerDensity from MicrowattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicFoot(double microwattspercubicfoot) -#else - public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspercubicfoot) -#endif - { - double value = (double) microwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); - } - - /// - /// Get PowerDensity from MicrowattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicInch(double microwattspercubicinch) -#else - public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspercubicinch) -#endif - { - double value = (double) microwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); - } - - /// - /// Get PowerDensity from MicrowattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicMeter(double microwattspercubicmeter) -#else - public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattspercubicmeter) -#endif - { - double value = (double) microwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); - } - - /// - /// Get PowerDensity from MicrowattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerLiter(double microwattsperliter) -#else - public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperliter) -#endif - { - double value = (double) microwattsperliter; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); - } - - /// - /// Get PowerDensity from MilliwattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicFoot(double milliwattspercubicfoot) -#else - public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspercubicfoot) -#endif - { - double value = (double) milliwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); - } - - /// - /// Get PowerDensity from MilliwattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicInch(double milliwattspercubicinch) -#else - public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspercubicinch) -#endif - { - double value = (double) milliwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); - } - - /// - /// Get PowerDensity from MilliwattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicMeter(double milliwattspercubicmeter) -#else - public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattspercubicmeter) -#endif - { - double value = (double) milliwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); - } - - /// - /// Get PowerDensity from MilliwattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerLiter(double milliwattsperliter) -#else - public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperliter) -#endif - { - double value = (double) milliwattsperliter; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); - } - - /// - /// Get PowerDensity from NanowattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicFoot(double nanowattspercubicfoot) -#else - public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattspercubicfoot) -#endif - { - double value = (double) nanowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); - } - - /// - /// Get PowerDensity from NanowattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicInch(double nanowattspercubicinch) -#else - public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattspercubicinch) -#endif - { - double value = (double) nanowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); - } - - /// - /// Get PowerDensity from NanowattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicMeter(double nanowattspercubicmeter) -#else - public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattspercubicmeter) -#endif - { - double value = (double) nanowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); - } - - /// - /// Get PowerDensity from NanowattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerLiter(double nanowattsperliter) -#else - public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter) -#endif - { - double value = (double) nanowattsperliter; - return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); - } - - /// - /// Get PowerDensity from PicowattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicFoot(double picowattspercubicfoot) -#else - public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattspercubicfoot) -#endif - { - double value = (double) picowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); - } - - /// - /// Get PowerDensity from PicowattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicInch(double picowattspercubicinch) -#else - public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattspercubicinch) -#endif - { - double value = (double) picowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); - } - - /// - /// Get PowerDensity from PicowattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicMeter(double picowattspercubicmeter) -#else - public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattspercubicmeter) -#endif - { - double value = (double) picowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); - } - - /// - /// Get PowerDensity from PicowattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerLiter(double picowattsperliter) -#else - public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter) -#endif - { - double value = (double) picowattsperliter; - return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); - } - - /// - /// Get PowerDensity from TerawattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicFoot(double terawattspercubicfoot) -#else - public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattspercubicfoot) -#endif - { - double value = (double) terawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); - } - - /// - /// Get PowerDensity from TerawattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicInch(double terawattspercubicinch) -#else - public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattspercubicinch) -#endif - { - double value = (double) terawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); - } - - /// - /// Get PowerDensity from TerawattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicMeter(double terawattspercubicmeter) -#else - public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattspercubicmeter) -#endif - { - double value = (double) terawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); - } - - /// - /// Get PowerDensity from TerawattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerLiter(double terawattsperliter) -#else - public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter) -#endif - { - double value = (double) terawattsperliter; - return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); - } - - /// - /// Get PowerDensity from WattsPerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicFoot(double wattspercubicfoot) -#else - public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot) -#endif - { - double value = (double) wattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); - } - - /// - /// Get PowerDensity from WattsPerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicInch(double wattspercubicinch) -#else - public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch) -#endif - { - double value = (double) wattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); - } - - /// - /// Get PowerDensity from WattsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicMeter(double wattspercubicmeter) -#else - public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmeter) -#endif - { - double value = (double) wattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); - } - - /// - /// Get PowerDensity from WattsPerLiter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerLiter(double wattsperliter) -#else - public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) -#endif - { - double value = (double) wattsperliter; - return new PowerDensity(value, PowerDensityUnit.WattPerLiter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PowerDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PowerDensity From(double value, PowerDensityUnit fromUnit) -#else - public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) -#endif - { - return new PowerDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is PowerDensity)) throw new ArgumentException("Expected type PowerDensity.", nameof(obj)); - - return CompareTo((PowerDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(PowerDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PowerDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PowerDensity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerDensity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PowerDensity to another PowerDensity with the unit representation . - /// - /// A PowerDensity with the specified unit. - public PowerDensity ToUnit(PowerDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PowerDensity(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 AsBaseUnit() - { - switch(Unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (_value*6.102374409473228e4) * 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (_value) * 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (_value*1.0e3) * 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (_value) * 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (_value*1.0e3) * 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (_value*6.102374409473228e4) * 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (_value) * 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (_value*1.0e3) * 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (_value*6.102374409473228e4) * 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (_value) * 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (_value*1.0e3) * 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (_value*6.102374409473228e4) * 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (_value) * 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (_value*1.0e3) * 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (_value) * 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (_value*1.0e3) * 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (_value) * 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (_value*1.0e3) * 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (_value) * 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (_value*1.0e3) * 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (_value) * 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (_value*1.0e3) * 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (_value*6.102374409473228e4) * 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (_value) * 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (_value*1.0e3) * 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return _value*3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return _value*6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return _value; - case PowerDensityUnit.WattPerLiter: return _value*1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PowerDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (baseUnitValue) / 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (baseUnitValue/1.0e3) / 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (baseUnitValue) / 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (baseUnitValue/1.0e3) / 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (baseUnitValue) / 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (baseUnitValue/1.0e3) / 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (baseUnitValue) / 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (baseUnitValue/1.0e3) / 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (baseUnitValue) / 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (baseUnitValue/1.0e3) / 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (baseUnitValue) / 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (baseUnitValue/1.0e3) / 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (baseUnitValue) / 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (baseUnitValue/1.0e3) / 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (baseUnitValue) / 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (baseUnitValue/1.0e3) / 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (baseUnitValue) / 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (baseUnitValue/1.0e3) / 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (baseUnitValue) / 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (baseUnitValue/1.0e3) / 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return baseUnitValue/3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return baseUnitValue/6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return baseUnitValue; - case PowerDensityUnit.WattPerLiter: return baseUnitValue/1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 PowerDensity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PowerDensity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerDensityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PowerDensityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static PowerDensity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PowerDensity result) - { - result = default(PowerDensity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PowerDensityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PowerDensityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PowerDensityUnit unit) - { - unit = PowerDensityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PowerDensityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PowerDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of PowerDensity - /// - public static PowerDensity MaxValue => new PowerDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of PowerDensity - /// - public static PowerDensity MinValue => new PowerDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => PowerDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PowerDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs b/Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs deleted file mode 100644 index 66d9f5d959..0000000000 --- a/Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs +++ /dev/null @@ -1,558 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The strength of a signal expressed in decibels (dB) relative to one watt. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class PowerRatio : IQuantity -#else - public partial struct PowerRatio : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerRatioUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static PowerRatio() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - PowerRatio(double numericValue, PowerRatioUnit unit) - { - if(unit == PowerRatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.PowerRatio; - - /// - /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. - /// - public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the PowerRatio quantity. - /// - public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); - - /// - /// Get PowerRatio in DecibelMilliwatts. - /// - public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); - - /// - /// Get PowerRatio in DecibelWatts. - /// - public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. - /// - public static PowerRatio Zero => new PowerRatio(0, BaseUnit); - - /// - /// Get PowerRatio from DecibelMilliwatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerRatio FromDecibelMilliwatts(double decibelmilliwatts) -#else - public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) -#endif - { - double value = (double) decibelmilliwatts; - return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); - } - - /// - /// Get PowerRatio from DecibelWatts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerRatio FromDecibelWatts(double decibelwatts) -#else - public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) -#endif - { - double value = (double) decibelwatts; - return new PowerRatio(value, PowerRatioUnit.DecibelWatt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PowerRatio unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PowerRatio From(double value, PowerRatioUnit fromUnit) -#else - public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) -#endif - { - return new PowerRatio((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerRatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is PowerRatio)) throw new ArgumentException("Expected type PowerRatio.", nameof(obj)); - - return CompareTo((PowerRatio)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(PowerRatio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PowerRatio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PowerRatio other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerRatio. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerRatioUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PowerRatio to another PowerRatio with the unit representation . - /// - /// A PowerRatio with the specified unit. - public PowerRatio ToUnit(PowerRatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PowerRatio(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 AsBaseUnit() - { - switch(Unit) - { - case PowerRatioUnit.DecibelMilliwatt: return _value - 30; - case PowerRatioUnit.DecibelWatt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PowerRatioUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerRatioUnit.DecibelMilliwatt: return baseUnitValue + 30; - case PowerRatioUnit.DecibelWatt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 PowerRatio Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PowerRatio result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerRatioUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PowerRatioUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static PowerRatio ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PowerRatio result) - { - result = default(PowerRatio); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PowerRatioUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PowerRatioUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerRatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PowerRatioUnit unit) - { - unit = PowerRatioUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PowerRatioUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PowerRatioUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of PowerRatio - /// - public static PowerRatio MaxValue => new PowerRatio(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of PowerRatio - /// - public static PowerRatio MinValue => new PowerRatio(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => PowerRatio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PowerRatio.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Pressure.Common.g.cs b/Common/GeneratedCode/Quantities/Pressure.Common.g.cs deleted file mode 100644 index baadedff81..0000000000 --- a/Common/GeneratedCode/Quantities/Pressure.Common.g.cs +++ /dev/null @@ -1,1329 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Pressure : IQuantity -#else - public partial struct Pressure : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PressureUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Pressure() - { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Pressure(double numericValue, PressureUnit unit) - { - if(unit == PressureUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Pressure; - - /// - /// The base unit of Pressure, which is Pascal. All conversions go via this value. - /// - public static PressureUnit BaseUnit => PressureUnit.Pascal; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Pressure quantity. - /// - public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); - - /// - /// Get Pressure in Atmospheres. - /// - public double Atmospheres => As(PressureUnit.Atmosphere); - - /// - /// Get Pressure in Bars. - /// - public double Bars => As(PressureUnit.Bar); - - /// - /// Get Pressure in Centibars. - /// - public double Centibars => As(PressureUnit.Centibar); - - /// - /// Get Pressure in Decapascals. - /// - public double Decapascals => As(PressureUnit.Decapascal); - - /// - /// Get Pressure in Decibars. - /// - public double Decibars => As(PressureUnit.Decibar); - - /// - /// Get Pressure in FeetOfHead. - /// - public double FeetOfHead => As(PressureUnit.FootOfHead); - - /// - /// Get Pressure in Gigapascals. - /// - public double Gigapascals => As(PressureUnit.Gigapascal); - - /// - /// Get Pressure in Hectopascals. - /// - public double Hectopascals => As(PressureUnit.Hectopascal); - - /// - /// Get Pressure in InchesOfMercury. - /// - public double InchesOfMercury => As(PressureUnit.InchOfMercury); - - /// - /// Get Pressure in Kilobars. - /// - public double Kilobars => As(PressureUnit.Kilobar); - - /// - /// Get Pressure in KilogramsForcePerSquareCentimeter. - /// - public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); - - /// - /// Get Pressure in KilogramsForcePerSquareMeter. - /// - public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); - - /// - /// Get Pressure in KilogramsForcePerSquareMillimeter. - /// - public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); - - /// - /// Get Pressure in KilonewtonsPerSquareCentimeter. - /// - public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); - - /// - /// Get Pressure in KilonewtonsPerSquareMeter. - /// - public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); - - /// - /// Get Pressure in KilonewtonsPerSquareMillimeter. - /// - public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); - - /// - /// Get Pressure in Kilopascals. - /// - public double Kilopascals => As(PressureUnit.Kilopascal); - - /// - /// Get Pressure in KilopoundsForcePerSquareFoot. - /// - public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); - - /// - /// Get Pressure in KilopoundsForcePerSquareInch. - /// - public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); - - /// - /// Get Pressure in Megabars. - /// - public double Megabars => As(PressureUnit.Megabar); - - /// - /// Get Pressure in MeganewtonsPerSquareMeter. - /// - public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); - - /// - /// Get Pressure in Megapascals. - /// - public double Megapascals => As(PressureUnit.Megapascal); - - /// - /// Get Pressure in MetersOfHead. - /// - public double MetersOfHead => As(PressureUnit.MeterOfHead); - - /// - /// Get Pressure in Micropascals. - /// - public double Micropascals => As(PressureUnit.Micropascal); - - /// - /// Get Pressure in Millibars. - /// - public double Millibars => As(PressureUnit.Millibar); - - /// - /// Get Pressure in MillimetersOfMercury. - /// - public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); - - /// - /// Get Pressure in NewtonsPerSquareCentimeter. - /// - public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); - - /// - /// Get Pressure in NewtonsPerSquareMeter. - /// - public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); - - /// - /// Get Pressure in NewtonsPerSquareMillimeter. - /// - public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); - - /// - /// Get Pressure in Pascals. - /// - public double Pascals => As(PressureUnit.Pascal); - - /// - /// Get Pressure in PoundsForcePerSquareFoot. - /// - public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); - - /// - /// Get Pressure in PoundsForcePerSquareInch. - /// - public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); - - /// - /// Get Pressure in TechnicalAtmospheres. - /// - public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); - - /// - /// Get Pressure in TonnesForcePerSquareCentimeter. - /// - public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); - - /// - /// Get Pressure in TonnesForcePerSquareMeter. - /// - public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); - - /// - /// Get Pressure in TonnesForcePerSquareMillimeter. - /// - public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); - - /// - /// Get Pressure in Torrs. - /// - public double Torrs => As(PressureUnit.Torr); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. - /// - public static Pressure Zero => new Pressure(0, BaseUnit); - - /// - /// Get Pressure from Atmospheres. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromAtmospheres(double atmospheres) -#else - public static Pressure FromAtmospheres(QuantityValue atmospheres) -#endif - { - double value = (double) atmospheres; - return new Pressure(value, PressureUnit.Atmosphere); - } - - /// - /// Get Pressure from Bars. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromBars(double bars) -#else - public static Pressure FromBars(QuantityValue bars) -#endif - { - double value = (double) bars; - return new Pressure(value, PressureUnit.Bar); - } - - /// - /// Get Pressure from Centibars. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromCentibars(double centibars) -#else - public static Pressure FromCentibars(QuantityValue centibars) -#endif - { - double value = (double) centibars; - return new Pressure(value, PressureUnit.Centibar); - } - - /// - /// Get Pressure from Decapascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDecapascals(double decapascals) -#else - public static Pressure FromDecapascals(QuantityValue decapascals) -#endif - { - double value = (double) decapascals; - return new Pressure(value, PressureUnit.Decapascal); - } - - /// - /// Get Pressure from Decibars. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDecibars(double decibars) -#else - public static Pressure FromDecibars(QuantityValue decibars) -#endif - { - double value = (double) decibars; - return new Pressure(value, PressureUnit.Decibar); - } - - /// - /// Get Pressure from FeetOfHead. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromFeetOfHead(double feetofhead) -#else - public static Pressure FromFeetOfHead(QuantityValue feetofhead) -#endif - { - double value = (double) feetofhead; - return new Pressure(value, PressureUnit.FootOfHead); - } - - /// - /// Get Pressure from Gigapascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromGigapascals(double gigapascals) -#else - public static Pressure FromGigapascals(QuantityValue gigapascals) -#endif - { - double value = (double) gigapascals; - return new Pressure(value, PressureUnit.Gigapascal); - } - - /// - /// Get Pressure from Hectopascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromHectopascals(double hectopascals) -#else - public static Pressure FromHectopascals(QuantityValue hectopascals) -#endif - { - double value = (double) hectopascals; - return new Pressure(value, PressureUnit.Hectopascal); - } - - /// - /// Get Pressure from InchesOfMercury. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromInchesOfMercury(double inchesofmercury) -#else - public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) -#endif - { - double value = (double) inchesofmercury; - return new Pressure(value, PressureUnit.InchOfMercury); - } - - /// - /// Get Pressure from Kilobars. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilobars(double kilobars) -#else - public static Pressure FromKilobars(QuantityValue kilobars) -#endif - { - double value = (double) kilobars; - return new Pressure(value, PressureUnit.Kilobar); - } - - /// - /// Get Pressure from KilogramsForcePerSquareCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareCentimeter(double kilogramsforcepersquarecentimeter) -#else - public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) -#endif - { - double value = (double) kilogramsforcepersquarecentimeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); - } - - /// - /// Get Pressure from KilogramsForcePerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareMeter(double kilogramsforcepersquaremeter) -#else - public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) -#endif - { - double value = (double) kilogramsforcepersquaremeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); - } - - /// - /// Get Pressure from KilogramsForcePerSquareMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareMillimeter(double kilogramsforcepersquaremillimeter) -#else - public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) -#endif - { - double value = (double) kilogramsforcepersquaremillimeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); - } - - /// - /// Get Pressure from KilonewtonsPerSquareCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareCentimeter(double kilonewtonspersquarecentimeter) -#else - public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) -#endif - { - double value = (double) kilonewtonspersquarecentimeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); - } - - /// - /// Get Pressure from KilonewtonsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareMeter(double kilonewtonspersquaremeter) -#else - public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) -#endif - { - double value = (double) kilonewtonspersquaremeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); - } - - /// - /// Get Pressure from KilonewtonsPerSquareMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareMillimeter(double kilonewtonspersquaremillimeter) -#else - public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) -#endif - { - double value = (double) kilonewtonspersquaremillimeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); - } - - /// - /// Get Pressure from Kilopascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopascals(double kilopascals) -#else - public static Pressure FromKilopascals(QuantityValue kilopascals) -#endif - { - double value = (double) kilopascals; - return new Pressure(value, PressureUnit.Kilopascal); - } - - /// - /// Get Pressure from KilopoundsForcePerSquareFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareFoot(double kilopoundsforcepersquarefoot) -#else - public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) -#endif - { - double value = (double) kilopoundsforcepersquarefoot; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); - } - - /// - /// Get Pressure from KilopoundsForcePerSquareInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareInch(double kilopoundsforcepersquareinch) -#else - public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) -#endif - { - double value = (double) kilopoundsforcepersquareinch; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); - } - - /// - /// Get Pressure from Megabars. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMegabars(double megabars) -#else - public static Pressure FromMegabars(QuantityValue megabars) -#endif - { - double value = (double) megabars; - return new Pressure(value, PressureUnit.Megabar); - } - - /// - /// Get Pressure from MeganewtonsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMeganewtonsPerSquareMeter(double meganewtonspersquaremeter) -#else - public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspersquaremeter) -#endif - { - double value = (double) meganewtonspersquaremeter; - return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); - } - - /// - /// Get Pressure from Megapascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMegapascals(double megapascals) -#else - public static Pressure FromMegapascals(QuantityValue megapascals) -#endif - { - double value = (double) megapascals; - return new Pressure(value, PressureUnit.Megapascal); - } - - /// - /// Get Pressure from MetersOfHead. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMetersOfHead(double metersofhead) -#else - public static Pressure FromMetersOfHead(QuantityValue metersofhead) -#endif - { - double value = (double) metersofhead; - return new Pressure(value, PressureUnit.MeterOfHead); - } - - /// - /// Get Pressure from Micropascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMicropascals(double micropascals) -#else - public static Pressure FromMicropascals(QuantityValue micropascals) -#endif - { - double value = (double) micropascals; - return new Pressure(value, PressureUnit.Micropascal); - } - - /// - /// Get Pressure from Millibars. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillibars(double millibars) -#else - public static Pressure FromMillibars(QuantityValue millibars) -#endif - { - double value = (double) millibars; - return new Pressure(value, PressureUnit.Millibar); - } - - /// - /// Get Pressure from MillimetersOfMercury. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillimetersOfMercury(double millimetersofmercury) -#else - public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) -#endif - { - double value = (double) millimetersofmercury; - return new Pressure(value, PressureUnit.MillimeterOfMercury); - } - - /// - /// Get Pressure from NewtonsPerSquareCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareCentimeter(double newtonspersquarecentimeter) -#else - public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) -#endif - { - double value = (double) newtonspersquarecentimeter; - return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); - } - - /// - /// Get Pressure from NewtonsPerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareMeter(double newtonspersquaremeter) -#else - public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) -#endif - { - double value = (double) newtonspersquaremeter; - return new Pressure(value, PressureUnit.NewtonPerSquareMeter); - } - - /// - /// Get Pressure from NewtonsPerSquareMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareMillimeter(double newtonspersquaremillimeter) -#else - public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) -#endif - { - double value = (double) newtonspersquaremillimeter; - return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); - } - - /// - /// Get Pressure from Pascals. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPascals(double pascals) -#else - public static Pressure FromPascals(QuantityValue pascals) -#endif - { - double value = (double) pascals; - return new Pressure(value, PressureUnit.Pascal); - } - - /// - /// Get Pressure from PoundsForcePerSquareFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareFoot(double poundsforcepersquarefoot) -#else - public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) -#endif - { - double value = (double) poundsforcepersquarefoot; - return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); - } - - /// - /// Get Pressure from PoundsForcePerSquareInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareInch(double poundsforcepersquareinch) -#else - public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) -#endif - { - double value = (double) poundsforcepersquareinch; - return new Pressure(value, PressureUnit.PoundForcePerSquareInch); - } - - /// - /// Get Pressure from TechnicalAtmospheres. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTechnicalAtmospheres(double technicalatmospheres) -#else - public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) -#endif - { - double value = (double) technicalatmospheres; - return new Pressure(value, PressureUnit.TechnicalAtmosphere); - } - - /// - /// Get Pressure from TonnesForcePerSquareCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareCentimeter(double tonnesforcepersquarecentimeter) -#else - public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) -#endif - { - double value = (double) tonnesforcepersquarecentimeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); - } - - /// - /// Get Pressure from TonnesForcePerSquareMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareMeter(double tonnesforcepersquaremeter) -#else - public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) -#endif - { - double value = (double) tonnesforcepersquaremeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); - } - - /// - /// Get Pressure from TonnesForcePerSquareMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareMillimeter(double tonnesforcepersquaremillimeter) -#else - public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) -#endif - { - double value = (double) tonnesforcepersquaremillimeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); - } - - /// - /// Get Pressure from Torrs. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTorrs(double torrs) -#else - public static Pressure FromTorrs(QuantityValue torrs) -#endif - { - double value = (double) torrs; - return new Pressure(value, PressureUnit.Torr); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Pressure unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Pressure From(double value, PressureUnit fromUnit) -#else - public static Pressure From(QuantityValue value, PressureUnit fromUnit) -#endif - { - return new Pressure((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PressureUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Pressure)) throw new ArgumentException("Expected type Pressure.", nameof(obj)); - - return CompareTo((Pressure)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Pressure other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Pressure within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Pressure other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Pressure. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Pressure to another Pressure with the unit representation . - /// - /// A Pressure with the specified unit. - public Pressure ToUnit(PressureUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Pressure(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 AsBaseUnit() - { - switch(Unit) - { - case PressureUnit.Atmosphere: return _value*1.01325*1e5; - case PressureUnit.Bar: return _value*1e5; - case PressureUnit.Centibar: return (_value*1e5) * 1e-2d; - case PressureUnit.Decapascal: return (_value) * 1e1d; - case PressureUnit.Decibar: return (_value*1e5) * 1e-1d; - case PressureUnit.FootOfHead: return _value*2989.0669; - case PressureUnit.Gigapascal: return (_value) * 1e9d; - case PressureUnit.Hectopascal: return (_value) * 1e2d; - case PressureUnit.InchOfMercury: return _value/2.95299830714159e-4; - case PressureUnit.Kilobar: return (_value*1e5) * 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return _value*9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return _value*9.80665019960652; - case PressureUnit.KilogramForcePerSquareMillimeter: return _value*9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (_value*1e4) * 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (_value*1e6) * 1e3d; - case PressureUnit.Kilopascal: return (_value) * 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (_value*4.788025898033584e1) * 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (_value*6.894757293168361e3) * 1e3d; - case PressureUnit.Megabar: return (_value*1e5) * 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (_value) * 1e6d; - case PressureUnit.Megapascal: return (_value) * 1e6d; - case PressureUnit.MeterOfHead: return _value*9804.139432; - case PressureUnit.Micropascal: return (_value) * 1e-6d; - case PressureUnit.Millibar: return (_value*1e5) * 1e-3d; - case PressureUnit.MillimeterOfMercury: return _value/7.50061561302643e-3; - case PressureUnit.NewtonPerSquareCentimeter: return _value*1e4; - case PressureUnit.NewtonPerSquareMeter: return _value; - case PressureUnit.NewtonPerSquareMillimeter: return _value*1e6; - case PressureUnit.Pascal: return _value; - case PressureUnit.PoundForcePerSquareFoot: return _value*4.788025898033584e1; - case PressureUnit.PoundForcePerSquareInch: return _value*6.894757293168361e3; - case PressureUnit.TechnicalAtmosphere: return _value*9.80680592331*1e4; - case PressureUnit.TonneForcePerSquareCentimeter: return _value*9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return _value*9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return _value*9.80665e9; - case PressureUnit.Torr: return _value*1.3332266752*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PressureUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PressureUnit.Atmosphere: return baseUnitValue/(1.01325*1e5); - case PressureUnit.Bar: return baseUnitValue/1e5; - case PressureUnit.Centibar: return (baseUnitValue/1e5) / 1e-2d; - case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; - case PressureUnit.Decibar: return (baseUnitValue/1e5) / 1e-1d; - case PressureUnit.FootOfHead: return baseUnitValue*0.000334552565551; - case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; - case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; - case PressureUnit.InchOfMercury: return baseUnitValue*2.95299830714159e-4; - case PressureUnit.Kilobar: return (baseUnitValue/1e5) / 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue/9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue*0.101971619222242; - case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue/9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue/1e4) / 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue/1e6) / 1e3d; - case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue/4.788025898033584e1) / 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue/6.894757293168361e3) / 1e3d; - case PressureUnit.Megabar: return (baseUnitValue/1e5) / 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (baseUnitValue) / 1e6d; - case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; - case PressureUnit.MeterOfHead: return baseUnitValue*0.0001019977334; - case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; - case PressureUnit.Millibar: return (baseUnitValue/1e5) / 1e-3d; - case PressureUnit.MillimeterOfMercury: return baseUnitValue*7.50061561302643e-3; - case PressureUnit.NewtonPerSquareCentimeter: return baseUnitValue/1e4; - case PressureUnit.NewtonPerSquareMeter: return baseUnitValue; - case PressureUnit.NewtonPerSquareMillimeter: return baseUnitValue/1e6; - case PressureUnit.Pascal: return baseUnitValue; - case PressureUnit.PoundForcePerSquareFoot: return baseUnitValue/4.788025898033584e1; - case PressureUnit.PoundForcePerSquareInch: return baseUnitValue/6.894757293168361e3; - case PressureUnit.TechnicalAtmosphere: return baseUnitValue/(9.80680592331*1e4); - case PressureUnit.TonneForcePerSquareCentimeter: return baseUnitValue/9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return baseUnitValue/9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return baseUnitValue/9.80665e9; - case PressureUnit.Torr: return baseUnitValue/(1.3332266752*1e2); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Pressure Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Pressure result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PressureUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Pressure ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Pressure result) - { - result = default(Pressure); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PressureUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PressureUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PressureUnit unit) - { - unit = PressureUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PressureUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PressureUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Pressure - /// - public static Pressure MaxValue => new Pressure(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Pressure - /// - public static Pressure MinValue => new Pressure(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Pressure.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Pressure.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs b/Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs deleted file mode 100644 index db9a9d9670..0000000000 --- a/Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class PressureChangeRate : IQuantity -#else - public partial struct PressureChangeRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PressureChangeRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static PressureChangeRate() - { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - PressureChangeRate(double numericValue, PressureChangeRateUnit unit) - { - if(unit == PressureChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.PressureChangeRate; - - /// - /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. - /// - public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the PressureChangeRate quantity. - /// - public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); - - /// - /// Get PressureChangeRate in AtmospheresPerSecond. - /// - public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); - - /// - /// Get PressureChangeRate in KilopascalsPerSecond. - /// - public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); - - /// - /// Get PressureChangeRate in MegapascalsPerSecond. - /// - public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); - - /// - /// Get PressureChangeRate in PascalsPerSecond. - /// - public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. - /// - public static PressureChangeRate Zero => new PressureChangeRate(0, BaseUnit); - - /// - /// Get PressureChangeRate from AtmospheresPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromAtmospheresPerSecond(double atmospherespersecond) -#else - public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) -#endif - { - double value = (double) atmospherespersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); - } - - /// - /// Get PressureChangeRate from KilopascalsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromKilopascalsPerSecond(double kilopascalspersecond) -#else - public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) -#endif - { - double value = (double) kilopascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); - } - - /// - /// Get PressureChangeRate from MegapascalsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMegapascalsPerSecond(double megapascalspersecond) -#else - public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) -#endif - { - double value = (double) megapascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); - } - - /// - /// Get PressureChangeRate from PascalsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromPascalsPerSecond(double pascalspersecond) -#else - public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) -#endif - { - double value = (double) pascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PressureChangeRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PressureChangeRate From(double value, PressureChangeRateUnit fromUnit) -#else - public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) -#endif - { - return new PressureChangeRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PressureChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is PressureChangeRate)) throw new ArgumentException("Expected type PressureChangeRate.", nameof(obj)); - - return CompareTo((PressureChangeRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(PressureChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PressureChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PressureChangeRate other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PressureChangeRate. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureChangeRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . - /// - /// A PressureChangeRate with the specified unit. - public PressureChangeRate ToUnit(PressureChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PressureChangeRate(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 AsBaseUnit() - { - switch(Unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325*1e5; - case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; - case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; - case PressureChangeRateUnit.PascalPerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PressureChangeRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325*1e5); - case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; - case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; - case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 PressureChangeRate Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PressureChangeRate result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureChangeRateUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static PressureChangeRate ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PressureChangeRate result) - { - result = default(PressureChangeRate); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static PressureChangeRateUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == PressureChangeRateUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out PressureChangeRateUnit unit) - { - unit = PressureChangeRateUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == PressureChangeRateUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PressureChangeRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of PressureChangeRate - /// - public static PressureChangeRate MaxValue => new PressureChangeRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of PressureChangeRate - /// - public static PressureChangeRate MinValue => new PressureChangeRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => PressureChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Ratio.Common.g.cs b/Common/GeneratedCode/Quantities/Ratio.Common.g.cs deleted file mode 100644 index 2f15162ea9..0000000000 --- a/Common/GeneratedCode/Quantities/Ratio.Common.g.cs +++ /dev/null @@ -1,646 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Ratio : IQuantity -#else - public partial struct Ratio : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RatioUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Ratio() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Ratio(double numericValue, RatioUnit unit) - { - if(unit == RatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Ratio; - - /// - /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. - /// - public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Ratio quantity. - /// - public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); - - /// - /// Get Ratio in DecimalFractions. - /// - public double DecimalFractions => As(RatioUnit.DecimalFraction); - - /// - /// Get Ratio in PartsPerBillion. - /// - public double PartsPerBillion => As(RatioUnit.PartPerBillion); - - /// - /// Get Ratio in PartsPerMillion. - /// - public double PartsPerMillion => As(RatioUnit.PartPerMillion); - - /// - /// Get Ratio in PartsPerThousand. - /// - public double PartsPerThousand => As(RatioUnit.PartPerThousand); - - /// - /// Get Ratio in PartsPerTrillion. - /// - public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); - - /// - /// Get Ratio in Percent. - /// - public double Percent => As(RatioUnit.Percent); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. - /// - public static Ratio Zero => new Ratio(0, BaseUnit); - - /// - /// Get Ratio from DecimalFractions. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromDecimalFractions(double decimalfractions) -#else - public static Ratio FromDecimalFractions(QuantityValue decimalfractions) -#endif - { - double value = (double) decimalfractions; - return new Ratio(value, RatioUnit.DecimalFraction); - } - - /// - /// Get Ratio from PartsPerBillion. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerBillion(double partsperbillion) -#else - public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) -#endif - { - double value = (double) partsperbillion; - return new Ratio(value, RatioUnit.PartPerBillion); - } - - /// - /// Get Ratio from PartsPerMillion. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerMillion(double partspermillion) -#else - public static Ratio FromPartsPerMillion(QuantityValue partspermillion) -#endif - { - double value = (double) partspermillion; - return new Ratio(value, RatioUnit.PartPerMillion); - } - - /// - /// Get Ratio from PartsPerThousand. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerThousand(double partsperthousand) -#else - public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) -#endif - { - double value = (double) partsperthousand; - return new Ratio(value, RatioUnit.PartPerThousand); - } - - /// - /// Get Ratio from PartsPerTrillion. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerTrillion(double partspertrillion) -#else - public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) -#endif - { - double value = (double) partspertrillion; - return new Ratio(value, RatioUnit.PartPerTrillion); - } - - /// - /// Get Ratio from Percent. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPercent(double percent) -#else - public static Ratio FromPercent(QuantityValue percent) -#endif - { - double value = (double) percent; - return new Ratio(value, RatioUnit.Percent); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Ratio unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Ratio From(double value, RatioUnit fromUnit) -#else - public static Ratio From(QuantityValue value, RatioUnit fromUnit) -#endif - { - return new Ratio((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Ratio)) throw new ArgumentException("Expected type Ratio.", nameof(obj)); - - return CompareTo((Ratio)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Ratio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Ratio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Ratio. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Ratio to another Ratio with the unit representation . - /// - /// A Ratio with the specified unit. - public Ratio ToUnit(RatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Ratio(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 AsBaseUnit() - { - switch(Unit) - { - case RatioUnit.DecimalFraction: return _value; - case RatioUnit.PartPerBillion: return _value/1e9; - case RatioUnit.PartPerMillion: return _value/1e6; - case RatioUnit.PartPerThousand: return _value/1e3; - case RatioUnit.PartPerTrillion: return _value/1e12; - case RatioUnit.Percent: return _value/1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RatioUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RatioUnit.DecimalFraction: return baseUnitValue; - case RatioUnit.PartPerBillion: return baseUnitValue*1e9; - case RatioUnit.PartPerMillion: return baseUnitValue*1e6; - case RatioUnit.PartPerThousand: return baseUnitValue*1e3; - case RatioUnit.PartPerTrillion: return baseUnitValue*1e12; - case RatioUnit.Percent: return baseUnitValue*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Ratio Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Ratio result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RatioUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out RatioUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Ratio ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Ratio result) - { - result = default(Ratio); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static RatioUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == RatioUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out RatioUnit unit) - { - unit = RatioUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == RatioUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RatioUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Ratio - /// - public static Ratio MaxValue => new Ratio(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Ratio - /// - public static Ratio MinValue => new Ratio(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Ratio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Ratio.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs deleted file mode 100644 index b6e38f715b..0000000000 --- a/Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ReactiveEnergy : IQuantity -#else - public partial struct ReactiveEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReactiveEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ReactiveEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ReactiveEnergy(double numericValue, ReactiveEnergyUnit unit) - { - if(unit == ReactiveEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ReactiveEnergy; - - /// - /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. - /// - public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ReactiveEnergy quantity. - /// - public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); - - /// - /// Get ReactiveEnergy in KilovoltampereReactiveHours. - /// - public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); - - /// - /// Get ReactiveEnergy in MegavoltampereReactiveHours. - /// - public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); - - /// - /// Get ReactiveEnergy in VoltampereReactiveHours. - /// - public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. - /// - public static ReactiveEnergy Zero => new ReactiveEnergy(0, BaseUnit); - - /// - /// Get ReactiveEnergy from KilovoltampereReactiveHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromKilovoltampereReactiveHours(double kilovoltamperereactivehours) -#else - public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) -#endif - { - double value = (double) kilovoltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); - } - - /// - /// Get ReactiveEnergy from MegavoltampereReactiveHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromMegavoltampereReactiveHours(double megavoltamperereactivehours) -#else - public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) -#endif - { - double value = (double) megavoltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); - } - - /// - /// Get ReactiveEnergy from VoltampereReactiveHours. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromVoltampereReactiveHours(double voltamperereactivehours) -#else - public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) -#endif - { - double value = (double) voltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReactiveEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) -#else - public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) -#endif - { - return new ReactiveEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ReactiveEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ReactiveEnergy)) throw new ArgumentException("Expected type ReactiveEnergy.", nameof(obj)); - - return CompareTo((ReactiveEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ReactiveEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ReactiveEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReactiveEnergy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReactiveEnergy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactiveEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation . - /// - /// A ReactiveEnergy with the specified unit. - public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReactiveEnergy(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 AsBaseUnit() - { - switch(Unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (_value) * 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (_value) * 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReactiveEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (baseUnitValue) / 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (baseUnitValue) / 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ReactiveEnergy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactiveEnergyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ReactiveEnergy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ReactiveEnergy result) - { - result = default(ReactiveEnergy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ReactiveEnergyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ReactiveEnergyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactiveEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ReactiveEnergyUnit unit) - { - unit = ReactiveEnergyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ReactiveEnergyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ReactiveEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ReactiveEnergy - /// - public static ReactiveEnergy MaxValue => new ReactiveEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ReactiveEnergy - /// - public static ReactiveEnergy MinValue => new ReactiveEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ReactiveEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs b/Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs deleted file mode 100644 index e97faed80e..0000000000 --- a/Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs +++ /dev/null @@ -1,603 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ReactivePower : IQuantity -#else - public partial struct ReactivePower : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReactivePowerUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ReactivePower() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ReactivePower(double numericValue, ReactivePowerUnit unit) - { - if(unit == ReactivePowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ReactivePower; - - /// - /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. - /// - public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ReactivePower quantity. - /// - public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); - - /// - /// Get ReactivePower in GigavoltamperesReactive. - /// - public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); - - /// - /// Get ReactivePower in KilovoltamperesReactive. - /// - public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); - - /// - /// Get ReactivePower in MegavoltamperesReactive. - /// - public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); - - /// - /// Get ReactivePower in VoltamperesReactive. - /// - public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. - /// - public static ReactivePower Zero => new ReactivePower(0, BaseUnit); - - /// - /// Get ReactivePower from GigavoltamperesReactive. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromGigavoltamperesReactive(double gigavoltamperesreactive) -#else - public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) -#endif - { - double value = (double) gigavoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); - } - - /// - /// Get ReactivePower from KilovoltamperesReactive. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromKilovoltamperesReactive(double kilovoltamperesreactive) -#else - public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) -#endif - { - double value = (double) kilovoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); - } - - /// - /// Get ReactivePower from MegavoltamperesReactive. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromMegavoltamperesReactive(double megavoltamperesreactive) -#else - public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) -#endif - { - double value = (double) megavoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); - } - - /// - /// Get ReactivePower from VoltamperesReactive. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromVoltamperesReactive(double voltamperesreactive) -#else - public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) -#endif - { - double value = (double) voltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReactivePower unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReactivePower From(double value, ReactivePowerUnit fromUnit) -#else - public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) -#endif - { - return new ReactivePower((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ReactivePowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ReactivePower)) throw new ArgumentException("Expected type ReactivePower.", nameof(obj)); - - return CompareTo((ReactivePower)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ReactivePower other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ReactivePower within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReactivePower other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReactivePower. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactivePowerUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReactivePower to another ReactivePower with the unit representation . - /// - /// A ReactivePower with the specified unit. - public ReactivePower ToUnit(ReactivePowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReactivePower(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 AsBaseUnit() - { - switch(Unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (_value) * 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (_value) * 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (_value) * 1e6d; - case ReactivePowerUnit.VoltampereReactive: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReactivePowerUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (baseUnitValue) / 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (baseUnitValue) / 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (baseUnitValue) / 1e6d; - case ReactivePowerUnit.VoltampereReactive: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ReactivePower Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReactivePower result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactivePowerUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ReactivePowerUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ReactivePower ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ReactivePower result) - { - result = default(ReactivePower); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ReactivePowerUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ReactivePowerUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactivePowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ReactivePowerUnit unit) - { - unit = ReactivePowerUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ReactivePowerUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ReactivePowerUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ReactivePower - /// - public static ReactivePower MaxValue => new ReactivePower(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ReactivePower - /// - public static ReactivePower MinValue => new ReactivePower(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ReactivePower.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReactivePower.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs deleted file mode 100644 index 54863e9bca..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Angular acceleration is the rate of change of rotational speed. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalAcceleration : IQuantity -#else - public partial struct RotationalAcceleration : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalAccelerationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalAcceleration() - { - BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalAcceleration(double numericValue, RotationalAccelerationUnit unit) - { - if(unit == RotationalAccelerationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalAcceleration; - - /// - /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. - /// - public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalAcceleration quantity. - /// - public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); - - /// - /// Get RotationalAcceleration in DegreesPerSecondSquared. - /// - public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); - - /// - /// Get RotationalAcceleration in RadiansPerSecondSquared. - /// - public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); - - /// - /// Get RotationalAcceleration in RevolutionsPerMinutePerSecond. - /// - public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. - /// - public static RotationalAcceleration Zero => new RotationalAcceleration(0, BaseUnit); - - /// - /// Get RotationalAcceleration from DegreesPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromDegreesPerSecondSquared(double degreespersecondsquared) -#else - public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) -#endif - { - double value = (double) degreespersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); - } - - /// - /// Get RotationalAcceleration from RadiansPerSecondSquared. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRadiansPerSecondSquared(double radianspersecondsquared) -#else - public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) -#endif - { - double value = (double) radianspersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); - } - - /// - /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double revolutionsperminutepersecond) -#else - public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) -#endif - { - double value = (double) revolutionsperminutepersecond; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalAcceleration unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalAcceleration From(double value, RotationalAccelerationUnit fromUnit) -#else - public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) -#endif - { - return new RotationalAcceleration((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalAccelerationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalAcceleration)) throw new ArgumentException("Expected type RotationalAcceleration.", nameof(obj)); - - return CompareTo((RotationalAcceleration)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalAcceleration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalAcceleration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalAcceleration other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalAcceleration. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalAccelerationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . - /// - /// A RotationalAcceleration with the specified unit. - public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalAcceleration(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 AsBaseUnit() - { - switch(Unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI/180)*_value; - case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2*Math.PI)/60)*_value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalAccelerationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (180/Math.PI)*baseUnitValue; - case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60/(2*Math.PI))*baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 RotationalAcceleration Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalAcceleration result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalAccelerationUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static RotationalAcceleration ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalAcceleration result) - { - result = default(RotationalAcceleration); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static RotationalAccelerationUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == RotationalAccelerationUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalAccelerationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out RotationalAccelerationUnit unit) - { - unit = RotationalAccelerationUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == RotationalAccelerationUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalAccelerationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalAcceleration - /// - public static RotationalAcceleration MaxValue => new RotationalAcceleration(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalAcceleration - /// - public static RotationalAcceleration MinValue => new RotationalAcceleration(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalAcceleration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs deleted file mode 100644 index c03e2d0da3..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs +++ /dev/null @@ -1,801 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalSpeed : IQuantity -#else - public partial struct RotationalSpeed : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalSpeedUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalSpeed() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalSpeed(double numericValue, RotationalSpeedUnit unit) - { - if(unit == RotationalSpeedUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalSpeed; - - /// - /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. - /// - public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalSpeed quantity. - /// - public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); - - /// - /// Get RotationalSpeed in CentiradiansPerSecond. - /// - public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); - - /// - /// Get RotationalSpeed in DeciradiansPerSecond. - /// - public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); - - /// - /// Get RotationalSpeed in DegreesPerMinute. - /// - public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); - - /// - /// Get RotationalSpeed in DegreesPerSecond. - /// - public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); - - /// - /// Get RotationalSpeed in MicrodegreesPerSecond. - /// - public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); - - /// - /// Get RotationalSpeed in MicroradiansPerSecond. - /// - public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); - - /// - /// Get RotationalSpeed in MillidegreesPerSecond. - /// - public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); - - /// - /// Get RotationalSpeed in MilliradiansPerSecond. - /// - public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); - - /// - /// Get RotationalSpeed in NanodegreesPerSecond. - /// - public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); - - /// - /// Get RotationalSpeed in NanoradiansPerSecond. - /// - public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); - - /// - /// Get RotationalSpeed in RadiansPerSecond. - /// - public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); - - /// - /// Get RotationalSpeed in RevolutionsPerMinute. - /// - public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); - - /// - /// Get RotationalSpeed in RevolutionsPerSecond. - /// - public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. - /// - public static RotationalSpeed Zero => new RotationalSpeed(0, BaseUnit); - - /// - /// Get RotationalSpeed from CentiradiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromCentiradiansPerSecond(double centiradianspersecond) -#else - public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) -#endif - { - double value = (double) centiradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); - } - - /// - /// Get RotationalSpeed from DeciradiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDeciradiansPerSecond(double deciradianspersecond) -#else - public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) -#endif - { - double value = (double) deciradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); - } - - /// - /// Get RotationalSpeed from DegreesPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDegreesPerMinute(double degreesperminute) -#else - public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) -#endif - { - double value = (double) degreesperminute; - return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); - } - - /// - /// Get RotationalSpeed from DegreesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDegreesPerSecond(double degreespersecond) -#else - public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) -#endif - { - double value = (double) degreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); - } - - /// - /// Get RotationalSpeed from MicrodegreesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMicrodegreesPerSecond(double microdegreespersecond) -#else - public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) -#endif - { - double value = (double) microdegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); - } - - /// - /// Get RotationalSpeed from MicroradiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMicroradiansPerSecond(double microradianspersecond) -#else - public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) -#endif - { - double value = (double) microradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); - } - - /// - /// Get RotationalSpeed from MillidegreesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMillidegreesPerSecond(double millidegreespersecond) -#else - public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) -#endif - { - double value = (double) millidegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); - } - - /// - /// Get RotationalSpeed from MilliradiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMilliradiansPerSecond(double milliradianspersecond) -#else - public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) -#endif - { - double value = (double) milliradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); - } - - /// - /// Get RotationalSpeed from NanodegreesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromNanodegreesPerSecond(double nanodegreespersecond) -#else - public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) -#endif - { - double value = (double) nanodegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); - } - - /// - /// Get RotationalSpeed from NanoradiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromNanoradiansPerSecond(double nanoradianspersecond) -#else - public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) -#endif - { - double value = (double) nanoradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); - } - - /// - /// Get RotationalSpeed from RadiansPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRadiansPerSecond(double radianspersecond) -#else - public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) -#endif - { - double value = (double) radianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); - } - - /// - /// Get RotationalSpeed from RevolutionsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRevolutionsPerMinute(double revolutionsperminute) -#else - public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) -#endif - { - double value = (double) revolutionsperminute; - return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); - } - - /// - /// Get RotationalSpeed from RevolutionsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRevolutionsPerSecond(double revolutionspersecond) -#else - public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) -#endif - { - double value = (double) revolutionspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalSpeed unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) -#else - public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) -#endif - { - return new RotationalSpeed((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalSpeedUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalSpeed)) throw new ArgumentException("Expected type RotationalSpeed.", nameof(obj)); - - return CompareTo((RotationalSpeed)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalSpeed other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalSpeed within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalSpeed other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalSpeed. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalSpeedUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . - /// - /// A RotationalSpeed with the specified unit. - public RotationalSpeed ToUnit(RotationalSpeedUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalSpeed(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 AsBaseUnit() - { - switch(Unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (_value) * 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (_value) * 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (Math.PI/(180*60))*_value; - case RotationalSpeedUnit.DegreePerSecond: return (Math.PI/180)*_value; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((Math.PI/180)*_value) * 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (_value) * 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((Math.PI/180)*_value) * 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (_value) * 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((Math.PI/180)*_value) * 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (_value) * 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return _value; - case RotationalSpeedUnit.RevolutionPerMinute: return (_value*6.2831853072)/60; - case RotationalSpeedUnit.RevolutionPerSecond: return _value*6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalSpeedUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (baseUnitValue) / 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (baseUnitValue) / 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (180*60/Math.PI)*baseUnitValue; - case RotationalSpeedUnit.DegreePerSecond: return (180/Math.PI)*baseUnitValue; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return baseUnitValue; - case RotationalSpeedUnit.RevolutionPerMinute: return (baseUnitValue/6.2831853072)*60; - case RotationalSpeedUnit.RevolutionPerSecond: return baseUnitValue/6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 RotationalSpeed Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalSpeedUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static RotationalSpeed ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalSpeed result) - { - result = default(RotationalSpeed); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static RotationalSpeedUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == RotationalSpeedUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalSpeedUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out RotationalSpeedUnit unit) - { - unit = RotationalSpeedUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == RotationalSpeedUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalSpeedUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalSpeed - /// - public static RotationalSpeed MaxValue => new RotationalSpeed(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalSpeed - /// - public static RotationalSpeed MinValue => new RotationalSpeed(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalSpeed.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs deleted file mode 100644 index f3a2d2b280..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalStiffness : IQuantity -#else - public partial struct RotationalStiffness : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalStiffnessUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalStiffness() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalStiffness(double numericValue, RotationalStiffnessUnit unit) - { - if(unit == RotationalStiffnessUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalStiffness; - - /// - /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. - /// - public static RotationalStiffnessUnit BaseUnit => RotationalStiffnessUnit.NewtonMeterPerRadian; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalStiffness quantity. - /// - public static RotationalStiffnessUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); - - /// - /// Get RotationalStiffness in KilonewtonMetersPerRadian. - /// - public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); - - /// - /// Get RotationalStiffness in MeganewtonMetersPerRadian. - /// - public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); - - /// - /// Get RotationalStiffness in NewtonMetersPerRadian. - /// - public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. - /// - public static RotationalStiffness Zero => new RotationalStiffness(0, BaseUnit); - - /// - /// Get RotationalStiffness from KilonewtonMetersPerRadian. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilonewtonMetersPerRadian(double kilonewtonmetersperradian) -#else - public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue kilonewtonmetersperradian) -#endif - { - double value = (double) kilonewtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); - } - - /// - /// Get RotationalStiffness from MeganewtonMetersPerRadian. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMeganewtonMetersPerRadian(double meganewtonmetersperradian) -#else - public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue meganewtonmetersperradian) -#endif - { - double value = (double) meganewtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); - } - - /// - /// Get RotationalStiffness from NewtonMetersPerRadian. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNewtonMetersPerRadian(double newtonmetersperradian) -#else - public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newtonmetersperradian) -#endif - { - double value = (double) newtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalStiffness unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalStiffness From(double value, RotationalStiffnessUnit fromUnit) -#else - public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) -#endif - { - return new RotationalStiffness((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalStiffnessUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalStiffness)) throw new ArgumentException("Expected type RotationalStiffness.", nameof(obj)); - - return CompareTo((RotationalStiffness)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalStiffness other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalStiffness within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalStiffness other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffness. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . - /// - /// A RotationalStiffness with the specified unit. - public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalStiffness(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 AsBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (_value) * 1e3d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (_value) * 1e6d; - case RotationalStiffnessUnit.NewtonMeterPerRadian: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalStiffnessUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (baseUnitValue) / 1e3d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (baseUnitValue) / 1e6d; - case RotationalStiffnessUnit.NewtonMeterPerRadian: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 RotationalStiffness Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalStiffness result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static RotationalStiffness ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalStiffness result) - { - result = default(RotationalStiffness); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static RotationalStiffnessUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == RotationalStiffnessUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalStiffnessUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out RotationalStiffnessUnit unit) - { - unit = RotationalStiffnessUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == RotationalStiffnessUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalStiffnessUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalStiffness - /// - public static RotationalStiffness MaxValue => new RotationalStiffness(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalStiffness - /// - public static RotationalStiffness MinValue => new RotationalStiffness(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalStiffness.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs deleted file mode 100644 index d8b10b8930..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs +++ /dev/null @@ -1,581 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalStiffnessPerLength : IQuantity -#else - public partial struct RotationalStiffnessPerLength : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalStiffnessPerLengthUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalStiffnessPerLength() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalStiffnessPerLength(double numericValue, RotationalStiffnessPerLengthUnit unit) - { - if(unit == RotationalStiffnessPerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalStiffnessPerLength; - - /// - /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. - /// - public static RotationalStiffnessPerLengthUnit BaseUnit => RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalStiffnessPerLength quantity. - /// - public static RotationalStiffnessPerLengthUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); - - /// - /// Get RotationalStiffnessPerLength in KilonewtonMetersPerRadianPerMeter. - /// - public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - - /// - /// Get RotationalStiffnessPerLength in MeganewtonMetersPerRadianPerMeter. - /// - public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - - /// - /// Get RotationalStiffnessPerLength in NewtonMetersPerRadianPerMeter. - /// - public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. - /// - public static RotationalStiffnessPerLength Zero => new RotationalStiffnessPerLength(0, BaseUnit); - - /// - /// Get RotationalStiffnessPerLength from KilonewtonMetersPerRadianPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(double kilonewtonmetersperradianpermeter) -#else - public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue kilonewtonmetersperradianpermeter) -#endif - { - double value = (double) kilonewtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - } - - /// - /// Get RotationalStiffnessPerLength from MeganewtonMetersPerRadianPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(double meganewtonmetersperradianpermeter) -#else - public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue meganewtonmetersperradianpermeter) -#endif - { - double value = (double) meganewtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - } - - /// - /// Get RotationalStiffnessPerLength from NewtonMetersPerRadianPerMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(double newtonmetersperradianpermeter) -#else - public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue newtonmetersperradianpermeter) -#endif - { - double value = (double) newtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalStiffnessPerLength unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalStiffnessPerLength From(double value, RotationalStiffnessPerLengthUnit fromUnit) -#else - public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) -#endif - { - return new RotationalStiffnessPerLength((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalStiffnessPerLength)) throw new ArgumentException("Expected type RotationalStiffnessPerLength.", nameof(obj)); - - return CompareTo((RotationalStiffnessPerLength)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalStiffnessPerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalStiffnessPerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalStiffnessPerLength other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffnessPerLength. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessPerLengthUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . - /// - /// A RotationalStiffnessPerLength with the specified unit. - public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalStiffnessPerLength(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 AsBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (_value) * 1e3d; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (_value) * 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalStiffnessPerLengthUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e3d; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 RotationalStiffnessPerLength Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalStiffnessPerLength result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessPerLengthUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static RotationalStiffnessPerLength ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalStiffnessPerLength result) - { - result = default(RotationalStiffnessPerLength); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static RotationalStiffnessPerLengthUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == RotationalStiffnessPerLengthUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalStiffnessPerLengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out RotationalStiffnessPerLengthUnit unit) - { - unit = RotationalStiffnessPerLengthUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == RotationalStiffnessPerLengthUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalStiffnessPerLengthUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalStiffnessPerLength - /// - public static RotationalStiffnessPerLength MaxValue => new RotationalStiffnessPerLength(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalStiffnessPerLength - /// - public static RotationalStiffnessPerLength MinValue => new RotationalStiffnessPerLength(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalStiffnessPerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs b/Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs deleted file mode 100644 index 344b7d5050..0000000000 --- a/Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs +++ /dev/null @@ -1,536 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SolidAngle : IQuantity -#else - public partial struct SolidAngle : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SolidAngleUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SolidAngle() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - SolidAngle(double numericValue, SolidAngleUnit unit) - { - if(unit == SolidAngleUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SolidAngle; - - /// - /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. - /// - public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SolidAngle quantity. - /// - public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); - - /// - /// Get SolidAngle in Steradians. - /// - public double Steradians => As(SolidAngleUnit.Steradian); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. - /// - public static SolidAngle Zero => new SolidAngle(0, BaseUnit); - - /// - /// Get SolidAngle from Steradians. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SolidAngle FromSteradians(double steradians) -#else - public static SolidAngle FromSteradians(QuantityValue steradians) -#endif - { - double value = (double) steradians; - return new SolidAngle(value, SolidAngleUnit.Steradian); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SolidAngle unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SolidAngle From(double value, SolidAngleUnit fromUnit) -#else - public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) -#endif - { - return new SolidAngle((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SolidAngleUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SolidAngle)) throw new ArgumentException("Expected type SolidAngle.", nameof(obj)); - - return CompareTo((SolidAngle)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SolidAngle other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SolidAngle within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SolidAngle other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SolidAngle. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SolidAngleUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SolidAngle to another SolidAngle with the unit representation . - /// - /// A SolidAngle with the specified unit. - public SolidAngle ToUnit(SolidAngleUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SolidAngle(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 AsBaseUnit() - { - switch(Unit) - { - case SolidAngleUnit.Steradian: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SolidAngleUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SolidAngleUnit.Steradian: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 SolidAngle Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SolidAngle result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SolidAngleUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out SolidAngleUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static SolidAngle ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SolidAngle result) - { - result = default(SolidAngle); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static SolidAngleUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == SolidAngleUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SolidAngleUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out SolidAngleUnit unit) - { - unit = SolidAngleUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == SolidAngleUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SolidAngleUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SolidAngle - /// - public static SolidAngle MaxValue => new SolidAngle(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SolidAngle - /// - public static SolidAngle MinValue => new SolidAngle(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SolidAngle.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SolidAngle.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs deleted file mode 100644 index e93fce1dab..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The SpecificEnergy - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificEnergy : IQuantity -#else - public partial struct SpecificEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificEnergy() - { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificEnergy(double numericValue, SpecificEnergyUnit unit) - { - if(unit == SpecificEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificEnergy; - - /// - /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. - /// - public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificEnergy quantity. - /// - public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); - - /// - /// Get SpecificEnergy in CaloriesPerGram. - /// - public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); - - /// - /// Get SpecificEnergy in JoulesPerKilogram. - /// - public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); - - /// - /// Get SpecificEnergy in KilocaloriesPerGram. - /// - public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); - - /// - /// Get SpecificEnergy in KilojoulesPerKilogram. - /// - public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); - - /// - /// Get SpecificEnergy in KilowattHoursPerKilogram. - /// - public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); - - /// - /// Get SpecificEnergy in MegajoulesPerKilogram. - /// - public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); - - /// - /// Get SpecificEnergy in MegawattHoursPerKilogram. - /// - public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); - - /// - /// Get SpecificEnergy in WattHoursPerKilogram. - /// - public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. - /// - public static SpecificEnergy Zero => new SpecificEnergy(0, BaseUnit); - - /// - /// Get SpecificEnergy from CaloriesPerGram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) -#else - public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) -#endif - { - double value = (double) caloriespergram; - return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); - } - - /// - /// Get SpecificEnergy from JoulesPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) -#else - public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) -#endif - { - double value = (double) joulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); - } - - /// - /// Get SpecificEnergy from KilocaloriesPerGram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) -#else - public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) -#endif - { - double value = (double) kilocaloriespergram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); - } - - /// - /// Get SpecificEnergy from KilojoulesPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) -#else - public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) -#endif - { - double value = (double) kilojoulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); - } - - /// - /// Get SpecificEnergy from KilowattHoursPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) -#else - public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) -#endif - { - double value = (double) kilowatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); - } - - /// - /// Get SpecificEnergy from MegajoulesPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) -#else - public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) -#endif - { - double value = (double) megajoulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); - } - - /// - /// Get SpecificEnergy from MegawattHoursPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) -#else - public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) -#endif - { - double value = (double) megawatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); - } - - /// - /// Get SpecificEnergy from WattHoursPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) -#else - public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) -#endif - { - double value = (double) watthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) -#else - public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) -#endif - { - return new SpecificEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificEnergy)) throw new ArgumentException("Expected type SpecificEnergy.", nameof(obj)); - - return CompareTo((SpecificEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificEnergy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEnergy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation . - /// - /// A SpecificEnergy with the specified unit. - public SpecificEnergy ToUnit(SpecificEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificEnergy(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 AsBaseUnit() - { - switch(Unit) - { - case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3; - case SpecificEnergyUnit.JoulePerKilogram: return _value; - case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d; - case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3; - case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; - case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d; - case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 SpecificEnergy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEnergyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static SpecificEnergy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificEnergy result) - { - result = default(SpecificEnergy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static SpecificEnergyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == SpecificEnergyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out SpecificEnergyUnit unit) - { - unit = SpecificEnergyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == SpecificEnergyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificEnergy - /// - public static SpecificEnergy MaxValue => new SpecificEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificEnergy - /// - public static SpecificEnergy MinValue => new SpecificEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs deleted file mode 100644 index b94fb65d1d..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificEntropy : IQuantity -#else - public partial struct SpecificEntropy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificEntropyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificEntropy() - { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificEntropy(double numericValue, SpecificEntropyUnit unit) - { - if(unit == SpecificEntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificEntropy; - - /// - /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. - /// - public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificEntropy quantity. - /// - public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); - - /// - /// Get SpecificEntropy in CaloriesPerGramKelvin. - /// - public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); - - /// - /// Get SpecificEntropy in JoulesPerKilogramDegreeCelsius. - /// - public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - - /// - /// Get SpecificEntropy in JoulesPerKilogramKelvin. - /// - public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); - - /// - /// Get SpecificEntropy in KilocaloriesPerGramKelvin. - /// - public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); - - /// - /// Get SpecificEntropy in KilojoulesPerKilogramDegreeCelsius. - /// - public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - - /// - /// Get SpecificEntropy in KilojoulesPerKilogramKelvin. - /// - public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); - - /// - /// Get SpecificEntropy in MegajoulesPerKilogramDegreeCelsius. - /// - public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - - /// - /// Get SpecificEntropy in MegajoulesPerKilogramKelvin. - /// - public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. - /// - public static SpecificEntropy Zero => new SpecificEntropy(0, BaseUnit); - - /// - /// Get SpecificEntropy from CaloriesPerGramKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromCaloriesPerGramKelvin(double caloriespergramkelvin) -#else - public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) -#endif - { - double value = (double) caloriespergramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); - } - - /// - /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double joulesperkilogramdegreecelsius) -#else - public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) -#endif - { - double value = (double) joulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - } - - /// - /// Get SpecificEntropy from JoulesPerKilogramKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromJoulesPerKilogramKelvin(double joulesperkilogramkelvin) -#else - public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) -#endif - { - double value = (double) joulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); - } - - /// - /// Get SpecificEntropy from KilocaloriesPerGramKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilocaloriesPerGramKelvin(double kilocaloriespergramkelvin) -#else - public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) -#endif - { - double value = (double) kilocaloriespergramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); - } - - /// - /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double kilojoulesperkilogramdegreecelsius) -#else - public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) -#endif - { - double value = (double) kilojoulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - } - - /// - /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double kilojoulesperkilogramkelvin) -#else - public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) -#endif - { - double value = (double) kilojoulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); - } - - /// - /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double megajoulesperkilogramdegreecelsius) -#else - public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) -#endif - { - double value = (double) megajoulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - } - - /// - /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double megajoulesperkilogramkelvin) -#else - public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) -#endif - { - double value = (double) megajoulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificEntropy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) -#else - public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) -#endif - { - return new SpecificEntropy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificEntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificEntropy)) throw new ArgumentException("Expected type SpecificEntropy.", nameof(obj)); - - return CompareTo((SpecificEntropy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificEntropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificEntropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificEntropy other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEntropy. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEntropyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation . - /// - /// A SpecificEntropy with the specified unit. - public SpecificEntropy ToUnit(SpecificEntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificEntropy(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 AsBaseUnit() - { - switch(Unit) - { - case SpecificEntropyUnit.CaloriePerGramKelvin: return _value*4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return _value; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return _value; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (_value*4.184e3) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (_value) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (_value) * 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (_value) * 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificEntropyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificEntropyUnit.CaloriePerGramKelvin: return baseUnitValue/4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return baseUnitValue; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return baseUnitValue; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (baseUnitValue/4.184e3) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 SpecificEntropy Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEntropyUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static SpecificEntropy ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificEntropy result) - { - result = default(SpecificEntropy); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static SpecificEntropyUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == SpecificEntropyUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out SpecificEntropyUnit unit) - { - unit = SpecificEntropyUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == SpecificEntropyUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificEntropyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificEntropy - /// - public static SpecificEntropy MaxValue => new SpecificEntropy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificEntropy - /// - public static SpecificEntropy MinValue => new SpecificEntropy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificEntropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs deleted file mode 100644 index f56d086df0..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs +++ /dev/null @@ -1,559 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificVolume : IQuantity -#else - public partial struct SpecificVolume : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificVolumeUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificVolume() - { - BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificVolume(double numericValue, SpecificVolumeUnit unit) - { - if(unit == SpecificVolumeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificVolume; - - /// - /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. - /// - public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificVolume quantity. - /// - public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); - - /// - /// Get SpecificVolume in CubicFeetPerPound. - /// - public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); - - /// - /// Get SpecificVolume in CubicMetersPerKilogram. - /// - public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. - /// - public static SpecificVolume Zero => new SpecificVolume(0, BaseUnit); - - /// - /// Get SpecificVolume from CubicFeetPerPound. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromCubicFeetPerPound(double cubicfeetperpound) -#else - public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpound) -#endif - { - double value = (double) cubicfeetperpound; - return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); - } - - /// - /// Get SpecificVolume from CubicMetersPerKilogram. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromCubicMetersPerKilogram(double cubicmetersperkilogram) -#else - public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) -#endif - { - double value = (double) cubicmetersperkilogram; - return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificVolume unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) -#else - public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) -#endif - { - return new SpecificVolume((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificVolumeUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificVolume)) throw new ArgumentException("Expected type SpecificVolume.", nameof(obj)); - - return CompareTo((SpecificVolume)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificVolume other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificVolume within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificVolume other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificVolume. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificVolumeUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificVolume to another SpecificVolume with the unit representation . - /// - /// A SpecificVolume with the specified unit. - public SpecificVolume ToUnit(SpecificVolumeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificVolume(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 AsBaseUnit() - { - switch(Unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return _value/16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificVolumeUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return baseUnitValue*16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 SpecificVolume Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificVolume result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificVolumeUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static SpecificVolume ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificVolume result) - { - result = default(SpecificVolume); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static SpecificVolumeUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == SpecificVolumeUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificVolumeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out SpecificVolumeUnit unit) - { - unit = SpecificVolumeUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == SpecificVolumeUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificVolumeUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificVolume - /// - public static SpecificVolume MaxValue => new SpecificVolume(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificVolume - /// - public static SpecificVolume MinValue => new SpecificVolume(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificVolume.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs deleted file mode 100644 index 6ecacc9fec..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs +++ /dev/null @@ -1,889 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificWeight : IQuantity -#else - public partial struct SpecificWeight : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificWeightUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificWeight() - { - BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificWeight(double numericValue, SpecificWeightUnit unit) - { - if(unit == SpecificWeightUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificWeight; - - /// - /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. - /// - public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificWeight quantity. - /// - public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); - - /// - /// Get SpecificWeight in KilogramsForcePerCubicCentimeter. - /// - public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); - - /// - /// Get SpecificWeight in KilogramsForcePerCubicMeter. - /// - public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); - - /// - /// Get SpecificWeight in KilogramsForcePerCubicMillimeter. - /// - public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); - - /// - /// Get SpecificWeight in KilonewtonsPerCubicCentimeter. - /// - public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); - - /// - /// Get SpecificWeight in KilonewtonsPerCubicMeter. - /// - public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); - - /// - /// Get SpecificWeight in KilonewtonsPerCubicMillimeter. - /// - public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); - - /// - /// Get SpecificWeight in KilopoundsForcePerCubicFoot. - /// - public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); - - /// - /// Get SpecificWeight in KilopoundsForcePerCubicInch. - /// - public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); - - /// - /// Get SpecificWeight in MeganewtonsPerCubicMeter. - /// - public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); - - /// - /// Get SpecificWeight in NewtonsPerCubicCentimeter. - /// - public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); - - /// - /// Get SpecificWeight in NewtonsPerCubicMeter. - /// - public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); - - /// - /// Get SpecificWeight in NewtonsPerCubicMillimeter. - /// - public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); - - /// - /// Get SpecificWeight in PoundsForcePerCubicFoot. - /// - public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); - - /// - /// Get SpecificWeight in PoundsForcePerCubicInch. - /// - public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); - - /// - /// Get SpecificWeight in TonnesForcePerCubicCentimeter. - /// - public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); - - /// - /// Get SpecificWeight in TonnesForcePerCubicMeter. - /// - public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); - - /// - /// Get SpecificWeight in TonnesForcePerCubicMillimeter. - /// - public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. - /// - public static SpecificWeight Zero => new SpecificWeight(0, BaseUnit); - - /// - /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double kilogramsforcepercubiccentimeter) -#else - public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) -#endif - { - double value = (double) kilogramsforcepercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); - } - - /// - /// Get SpecificWeight from KilogramsForcePerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicMeter(double kilogramsforcepercubicmeter) -#else - public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) -#endif - { - double value = (double) kilogramsforcepercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); - } - - /// - /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double kilogramsforcepercubicmillimeter) -#else - public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) -#endif - { - double value = (double) kilogramsforcepercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); - } - - /// - /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double kilonewtonspercubiccentimeter) -#else - public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) -#endif - { - double value = (double) kilonewtonspercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); - } - - /// - /// Get SpecificWeight from KilonewtonsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicMeter(double kilonewtonspercubicmeter) -#else - public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) -#endif - { - double value = (double) kilonewtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); - } - - /// - /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double kilonewtonspercubicmillimeter) -#else - public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) -#endif - { - double value = (double) kilonewtonspercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); - } - - /// - /// Get SpecificWeight from KilopoundsForcePerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilopoundsForcePerCubicFoot(double kilopoundsforcepercubicfoot) -#else - public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) -#endif - { - double value = (double) kilopoundsforcepercubicfoot; - return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); - } - - /// - /// Get SpecificWeight from KilopoundsForcePerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilopoundsForcePerCubicInch(double kilopoundsforcepercubicinch) -#else - public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) -#endif - { - double value = (double) kilopoundsforcepercubicinch; - return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); - } - - /// - /// Get SpecificWeight from MeganewtonsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromMeganewtonsPerCubicMeter(double meganewtonspercubicmeter) -#else - public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewtonspercubicmeter) -#endif - { - double value = (double) meganewtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); - } - - /// - /// Get SpecificWeight from NewtonsPerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicCentimeter(double newtonspercubiccentimeter) -#else - public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) -#endif - { - double value = (double) newtonspercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); - } - - /// - /// Get SpecificWeight from NewtonsPerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicMeter(double newtonspercubicmeter) -#else - public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) -#endif - { - double value = (double) newtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); - } - - /// - /// Get SpecificWeight from NewtonsPerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicMillimeter(double newtonspercubicmillimeter) -#else - public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) -#endif - { - double value = (double) newtonspercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); - } - - /// - /// Get SpecificWeight from PoundsForcePerCubicFoot. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromPoundsForcePerCubicFoot(double poundsforcepercubicfoot) -#else - public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) -#endif - { - double value = (double) poundsforcepercubicfoot; - return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); - } - - /// - /// Get SpecificWeight from PoundsForcePerCubicInch. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromPoundsForcePerCubicInch(double poundsforcepercubicinch) -#else - public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) -#endif - { - double value = (double) poundsforcepercubicinch; - return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); - } - - /// - /// Get SpecificWeight from TonnesForcePerCubicCentimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicCentimeter(double tonnesforcepercubiccentimeter) -#else - public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) -#endif - { - double value = (double) tonnesforcepercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); - } - - /// - /// Get SpecificWeight from TonnesForcePerCubicMeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicMeter(double tonnesforcepercubicmeter) -#else - public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) -#endif - { - double value = (double) tonnesforcepercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); - } - - /// - /// Get SpecificWeight from TonnesForcePerCubicMillimeter. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicMillimeter(double tonnesforcepercubicmillimeter) -#else - public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) -#endif - { - double value = (double) tonnesforcepercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificWeight unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) -#else - public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) -#endif - { - return new SpecificWeight((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificWeightUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificWeight)) throw new ArgumentException("Expected type SpecificWeight.", nameof(obj)); - - return CompareTo((SpecificWeight)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificWeight other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificWeight within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificWeight other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificWeight. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificWeightUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificWeight to another SpecificWeight with the unit representation . - /// - /// A SpecificWeight with the specified unit. - public SpecificWeight ToUnit(SpecificWeightUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificWeight(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 AsBaseUnit() - { - switch(Unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return _value*9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return _value*9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return _value*9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (_value*1000000) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (_value) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (_value*1000000000) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (_value*1.570874638462462e2) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (_value*2.714471375263134e5) * 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (_value) * 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return _value*1000000; - case SpecificWeightUnit.NewtonPerCubicMeter: return _value; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return _value*1000000000; - case SpecificWeightUnit.PoundForcePerCubicFoot: return _value*1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return _value*2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return _value*9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return _value*9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return _value*9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificWeightUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return baseUnitValue/9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return baseUnitValue/9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return baseUnitValue/9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (baseUnitValue*0.000001) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (baseUnitValue) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (baseUnitValue*0.000000001) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (baseUnitValue/1.570874638462462e2) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (baseUnitValue/2.714471375263134e5) / 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (baseUnitValue) / 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return baseUnitValue*0.000001; - case SpecificWeightUnit.NewtonPerCubicMeter: return baseUnitValue; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return baseUnitValue*0.000000001; - case SpecificWeightUnit.PoundForcePerCubicFoot: return baseUnitValue/1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return baseUnitValue/2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return baseUnitValue/9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return baseUnitValue/9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return baseUnitValue/9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 SpecificWeight Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificWeight result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificWeightUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out SpecificWeightUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static SpecificWeight ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificWeight result) - { - result = default(SpecificWeight); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static SpecificWeightUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == SpecificWeightUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificWeightUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out SpecificWeightUnit unit) - { - unit = SpecificWeightUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == SpecificWeightUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificWeightUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificWeight - /// - public static SpecificWeight MaxValue => new SpecificWeight(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificWeight - /// - public static SpecificWeight MinValue => new SpecificWeight(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificWeight.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Speed.Common.g.cs b/Common/GeneratedCode/Quantities/Speed.Common.g.cs deleted file mode 100644 index 630d1f1ff3..0000000000 --- a/Common/GeneratedCode/Quantities/Speed.Common.g.cs +++ /dev/null @@ -1,1219 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Speed : IQuantity -#else - public partial struct Speed : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpeedUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Speed() - { - BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Speed(double numericValue, SpeedUnit unit) - { - if(unit == SpeedUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Speed; - - /// - /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. - /// - public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Speed quantity. - /// - public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); - - /// - /// Get Speed in CentimetersPerHour. - /// - public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); - - /// - /// Get Speed in CentimetersPerMinutes. - /// - public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); - - /// - /// Get Speed in CentimetersPerSecond. - /// - public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); - - /// - /// Get Speed in DecimetersPerMinutes. - /// - public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); - - /// - /// Get Speed in DecimetersPerSecond. - /// - public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); - - /// - /// Get Speed in FeetPerHour. - /// - public double FeetPerHour => As(SpeedUnit.FootPerHour); - - /// - /// Get Speed in FeetPerMinute. - /// - public double FeetPerMinute => As(SpeedUnit.FootPerMinute); - - /// - /// Get Speed in FeetPerSecond. - /// - public double FeetPerSecond => As(SpeedUnit.FootPerSecond); - - /// - /// Get Speed in InchesPerHour. - /// - public double InchesPerHour => As(SpeedUnit.InchPerHour); - - /// - /// Get Speed in InchesPerMinute. - /// - public double InchesPerMinute => As(SpeedUnit.InchPerMinute); - - /// - /// Get Speed in InchesPerSecond. - /// - public double InchesPerSecond => As(SpeedUnit.InchPerSecond); - - /// - /// Get Speed in KilometersPerHour. - /// - public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); - - /// - /// Get Speed in KilometersPerMinutes. - /// - public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); - - /// - /// Get Speed in KilometersPerSecond. - /// - public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); - - /// - /// Get Speed in Knots. - /// - public double Knots => As(SpeedUnit.Knot); - - /// - /// Get Speed in MetersPerHour. - /// - public double MetersPerHour => As(SpeedUnit.MeterPerHour); - - /// - /// Get Speed in MetersPerMinutes. - /// - public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); - - /// - /// Get Speed in MetersPerSecond. - /// - public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); - - /// - /// Get Speed in MicrometersPerMinutes. - /// - public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); - - /// - /// Get Speed in MicrometersPerSecond. - /// - public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); - - /// - /// Get Speed in MilesPerHour. - /// - public double MilesPerHour => As(SpeedUnit.MilePerHour); - - /// - /// Get Speed in MillimetersPerHour. - /// - public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); - - /// - /// Get Speed in MillimetersPerMinutes. - /// - public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); - - /// - /// Get Speed in MillimetersPerSecond. - /// - public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); - - /// - /// Get Speed in NanometersPerMinutes. - /// - public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); - - /// - /// Get Speed in NanometersPerSecond. - /// - public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); - - /// - /// Get Speed in UsSurveyFeetPerHour. - /// - public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); - - /// - /// Get Speed in UsSurveyFeetPerMinute. - /// - public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); - - /// - /// Get Speed in UsSurveyFeetPerSecond. - /// - public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); - - /// - /// Get Speed in YardsPerHour. - /// - public double YardsPerHour => As(SpeedUnit.YardPerHour); - - /// - /// Get Speed in YardsPerMinute. - /// - public double YardsPerMinute => As(SpeedUnit.YardPerMinute); - - /// - /// Get Speed in YardsPerSecond. - /// - public double YardsPerSecond => As(SpeedUnit.YardPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. - /// - public static Speed Zero => new Speed(0, BaseUnit); - - /// - /// Get Speed from CentimetersPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerHour(double centimetersperhour) -#else - public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) -#endif - { - double value = (double) centimetersperhour; - return new Speed(value, SpeedUnit.CentimeterPerHour); - } - - /// - /// Get Speed from CentimetersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerMinutes(double centimetersperminutes) -#else - public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) -#endif - { - double value = (double) centimetersperminutes; - return new Speed(value, SpeedUnit.CentimeterPerMinute); - } - - /// - /// Get Speed from CentimetersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerSecond(double centimeterspersecond) -#else - public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) -#endif - { - double value = (double) centimeterspersecond; - return new Speed(value, SpeedUnit.CentimeterPerSecond); - } - - /// - /// Get Speed from DecimetersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromDecimetersPerMinutes(double decimetersperminutes) -#else - public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) -#endif - { - double value = (double) decimetersperminutes; - return new Speed(value, SpeedUnit.DecimeterPerMinute); - } - - /// - /// Get Speed from DecimetersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromDecimetersPerSecond(double decimeterspersecond) -#else - public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) -#endif - { - double value = (double) decimeterspersecond; - return new Speed(value, SpeedUnit.DecimeterPerSecond); - } - - /// - /// Get Speed from FeetPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerHour(double feetperhour) -#else - public static Speed FromFeetPerHour(QuantityValue feetperhour) -#endif - { - double value = (double) feetperhour; - return new Speed(value, SpeedUnit.FootPerHour); - } - - /// - /// Get Speed from FeetPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerMinute(double feetperminute) -#else - public static Speed FromFeetPerMinute(QuantityValue feetperminute) -#endif - { - double value = (double) feetperminute; - return new Speed(value, SpeedUnit.FootPerMinute); - } - - /// - /// Get Speed from FeetPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerSecond(double feetpersecond) -#else - public static Speed FromFeetPerSecond(QuantityValue feetpersecond) -#endif - { - double value = (double) feetpersecond; - return new Speed(value, SpeedUnit.FootPerSecond); - } - - /// - /// Get Speed from InchesPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerHour(double inchesperhour) -#else - public static Speed FromInchesPerHour(QuantityValue inchesperhour) -#endif - { - double value = (double) inchesperhour; - return new Speed(value, SpeedUnit.InchPerHour); - } - - /// - /// Get Speed from InchesPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerMinute(double inchesperminute) -#else - public static Speed FromInchesPerMinute(QuantityValue inchesperminute) -#endif - { - double value = (double) inchesperminute; - return new Speed(value, SpeedUnit.InchPerMinute); - } - - /// - /// Get Speed from InchesPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerSecond(double inchespersecond) -#else - public static Speed FromInchesPerSecond(QuantityValue inchespersecond) -#endif - { - double value = (double) inchespersecond; - return new Speed(value, SpeedUnit.InchPerSecond); - } - - /// - /// Get Speed from KilometersPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerHour(double kilometersperhour) -#else - public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) -#endif - { - double value = (double) kilometersperhour; - return new Speed(value, SpeedUnit.KilometerPerHour); - } - - /// - /// Get Speed from KilometersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerMinutes(double kilometersperminutes) -#else - public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) -#endif - { - double value = (double) kilometersperminutes; - return new Speed(value, SpeedUnit.KilometerPerMinute); - } - - /// - /// Get Speed from KilometersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerSecond(double kilometerspersecond) -#else - public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) -#endif - { - double value = (double) kilometerspersecond; - return new Speed(value, SpeedUnit.KilometerPerSecond); - } - - /// - /// Get Speed from Knots. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKnots(double knots) -#else - public static Speed FromKnots(QuantityValue knots) -#endif - { - double value = (double) knots; - return new Speed(value, SpeedUnit.Knot); - } - - /// - /// Get Speed from MetersPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerHour(double metersperhour) -#else - public static Speed FromMetersPerHour(QuantityValue metersperhour) -#endif - { - double value = (double) metersperhour; - return new Speed(value, SpeedUnit.MeterPerHour); - } - - /// - /// Get Speed from MetersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerMinutes(double metersperminutes) -#else - public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) -#endif - { - double value = (double) metersperminutes; - return new Speed(value, SpeedUnit.MeterPerMinute); - } - - /// - /// Get Speed from MetersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerSecond(double meterspersecond) -#else - public static Speed FromMetersPerSecond(QuantityValue meterspersecond) -#endif - { - double value = (double) meterspersecond; - return new Speed(value, SpeedUnit.MeterPerSecond); - } - - /// - /// Get Speed from MicrometersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMicrometersPerMinutes(double micrometersperminutes) -#else - public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) -#endif - { - double value = (double) micrometersperminutes; - return new Speed(value, SpeedUnit.MicrometerPerMinute); - } - - /// - /// Get Speed from MicrometersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMicrometersPerSecond(double micrometerspersecond) -#else - public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) -#endif - { - double value = (double) micrometerspersecond; - return new Speed(value, SpeedUnit.MicrometerPerSecond); - } - - /// - /// Get Speed from MilesPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMilesPerHour(double milesperhour) -#else - public static Speed FromMilesPerHour(QuantityValue milesperhour) -#endif - { - double value = (double) milesperhour; - return new Speed(value, SpeedUnit.MilePerHour); - } - - /// - /// Get Speed from MillimetersPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerHour(double millimetersperhour) -#else - public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) -#endif - { - double value = (double) millimetersperhour; - return new Speed(value, SpeedUnit.MillimeterPerHour); - } - - /// - /// Get Speed from MillimetersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerMinutes(double millimetersperminutes) -#else - public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) -#endif - { - double value = (double) millimetersperminutes; - return new Speed(value, SpeedUnit.MillimeterPerMinute); - } - - /// - /// Get Speed from MillimetersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerSecond(double millimeterspersecond) -#else - public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) -#endif - { - double value = (double) millimeterspersecond; - return new Speed(value, SpeedUnit.MillimeterPerSecond); - } - - /// - /// Get Speed from NanometersPerMinutes. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromNanometersPerMinutes(double nanometersperminutes) -#else - public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) -#endif - { - double value = (double) nanometersperminutes; - return new Speed(value, SpeedUnit.NanometerPerMinute); - } - - /// - /// Get Speed from NanometersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromNanometersPerSecond(double nanometerspersecond) -#else - public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) -#endif - { - double value = (double) nanometerspersecond; - return new Speed(value, SpeedUnit.NanometerPerSecond); - } - - /// - /// Get Speed from UsSurveyFeetPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerHour(double ussurveyfeetperhour) -#else - public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) -#endif - { - double value = (double) ussurveyfeetperhour; - return new Speed(value, SpeedUnit.UsSurveyFootPerHour); - } - - /// - /// Get Speed from UsSurveyFeetPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerMinute(double ussurveyfeetperminute) -#else - public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) -#endif - { - double value = (double) ussurveyfeetperminute; - return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); - } - - /// - /// Get Speed from UsSurveyFeetPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerSecond(double ussurveyfeetpersecond) -#else - public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) -#endif - { - double value = (double) ussurveyfeetpersecond; - return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); - } - - /// - /// Get Speed from YardsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerHour(double yardsperhour) -#else - public static Speed FromYardsPerHour(QuantityValue yardsperhour) -#endif - { - double value = (double) yardsperhour; - return new Speed(value, SpeedUnit.YardPerHour); - } - - /// - /// Get Speed from YardsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerMinute(double yardsperminute) -#else - public static Speed FromYardsPerMinute(QuantityValue yardsperminute) -#endif - { - double value = (double) yardsperminute; - return new Speed(value, SpeedUnit.YardPerMinute); - } - - /// - /// Get Speed from YardsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerSecond(double yardspersecond) -#else - public static Speed FromYardsPerSecond(QuantityValue yardspersecond) -#endif - { - double value = (double) yardspersecond; - return new Speed(value, SpeedUnit.YardPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Speed unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Speed From(double value, SpeedUnit fromUnit) -#else - public static Speed From(QuantityValue value, SpeedUnit fromUnit) -#endif - { - return new Speed((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpeedUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Speed)) throw new ArgumentException("Expected type Speed.", nameof(obj)); - - return CompareTo((Speed)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Speed other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Speed within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Speed. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpeedUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Speed to another Speed with the unit representation . - /// - /// A Speed with the specified unit. - public Speed ToUnit(SpeedUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Speed(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 AsBaseUnit() - { - switch(Unit) - { - case SpeedUnit.CentimeterPerHour: return (_value/3600) * 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (_value/60) * 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (_value/60) * 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; - case SpeedUnit.FootPerHour: return _value*0.3048/3600; - case SpeedUnit.FootPerMinute: return _value*0.3048/60; - case SpeedUnit.FootPerSecond: return _value*0.3048; - case SpeedUnit.InchPerHour: return (_value/3600)*2.54e-2; - case SpeedUnit.InchPerMinute: return (_value/60)*2.54e-2; - case SpeedUnit.InchPerSecond: return _value*2.54e-2; - case SpeedUnit.KilometerPerHour: return (_value/3600) * 1e3d; - case SpeedUnit.KilometerPerMinute: return (_value/60) * 1e3d; - case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; - case SpeedUnit.Knot: return _value*0.514444; - case SpeedUnit.MeterPerHour: return _value/3600; - case SpeedUnit.MeterPerMinute: return _value/60; - case SpeedUnit.MeterPerSecond: return _value; - case SpeedUnit.MicrometerPerMinute: return (_value/60) * 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; - case SpeedUnit.MilePerHour: return _value*0.44704; - case SpeedUnit.MillimeterPerHour: return (_value/3600) * 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (_value/60) * 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; - case SpeedUnit.NanometerPerMinute: return (_value/60) * 1e-9d; - case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (_value*1200/3937)/3600; - case SpeedUnit.UsSurveyFootPerMinute: return (_value*1200/3937)/60; - case SpeedUnit.UsSurveyFootPerSecond: return _value*1200/3937; - case SpeedUnit.YardPerHour: return _value*0.9144/3600; - case SpeedUnit.YardPerMinute: return _value*0.9144/60; - case SpeedUnit.YardPerSecond: return _value*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpeedUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpeedUnit.CentimeterPerHour: return (baseUnitValue*3600) / 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (baseUnitValue*60) / 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (baseUnitValue*60) / 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; - case SpeedUnit.FootPerHour: return baseUnitValue/0.3048*3600; - case SpeedUnit.FootPerMinute: return baseUnitValue/0.3048*60; - case SpeedUnit.FootPerSecond: return baseUnitValue/0.3048; - case SpeedUnit.InchPerHour: return (baseUnitValue/2.54e-2)*3600; - case SpeedUnit.InchPerMinute: return (baseUnitValue/2.54e-2)*60; - case SpeedUnit.InchPerSecond: return baseUnitValue/2.54e-2; - case SpeedUnit.KilometerPerHour: return (baseUnitValue*3600) / 1e3d; - case SpeedUnit.KilometerPerMinute: return (baseUnitValue*60) / 1e3d; - case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; - case SpeedUnit.Knot: return baseUnitValue/0.514444; - case SpeedUnit.MeterPerHour: return baseUnitValue*3600; - case SpeedUnit.MeterPerMinute: return baseUnitValue*60; - case SpeedUnit.MeterPerSecond: return baseUnitValue; - case SpeedUnit.MicrometerPerMinute: return (baseUnitValue*60) / 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; - case SpeedUnit.MilePerHour: return baseUnitValue/0.44704; - case SpeedUnit.MillimeterPerHour: return (baseUnitValue*3600) / 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (baseUnitValue*60) / 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; - case SpeedUnit.NanometerPerMinute: return (baseUnitValue*60) / 1e-9d; - case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue*3937/1200)*3600; - case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue*3937/1200)*60; - case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue*3937/1200; - case SpeedUnit.YardPerHour: return baseUnitValue/0.9144*3600; - case SpeedUnit.YardPerMinute: return baseUnitValue/0.9144*60; - case SpeedUnit.YardPerSecond: return baseUnitValue/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Speed Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Speed result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpeedUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out SpeedUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Speed ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Speed result) - { - result = default(Speed); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static SpeedUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == SpeedUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpeedUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out SpeedUnit unit) - { - unit = SpeedUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == SpeedUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpeedUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Speed - /// - public static Speed MaxValue => new Speed(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Speed - /// - public static Speed MinValue => new Speed(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Speed.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Speed.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Temperature.Common.g.cs b/Common/GeneratedCode/Quantities/Temperature.Common.g.cs deleted file mode 100644 index 5d4c748cb7..0000000000 --- a/Common/GeneratedCode/Quantities/Temperature.Common.g.cs +++ /dev/null @@ -1,691 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Temperature : IQuantity -#else - public partial struct Temperature : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Temperature() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Temperature(double numericValue, TemperatureUnit unit) - { - if(unit == TemperatureUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Temperature; - - /// - /// The base unit of Temperature, which is Kelvin. All conversions go via this value. - /// - public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Temperature quantity. - /// - public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); - - /// - /// Get Temperature in DegreesCelsius. - /// - public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); - - /// - /// Get Temperature in DegreesDelisle. - /// - public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); - - /// - /// Get Temperature in DegreesFahrenheit. - /// - public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); - - /// - /// Get Temperature in DegreesNewton. - /// - public double DegreesNewton => As(TemperatureUnit.DegreeNewton); - - /// - /// Get Temperature in DegreesRankine. - /// - public double DegreesRankine => As(TemperatureUnit.DegreeRankine); - - /// - /// Get Temperature in DegreesReaumur. - /// - public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); - - /// - /// Get Temperature in DegreesRoemer. - /// - public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); - - /// - /// Get Temperature in Kelvins. - /// - public double Kelvins => As(TemperatureUnit.Kelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. - /// - public static Temperature Zero => new Temperature(0, BaseUnit); - - /// - /// Get Temperature from DegreesCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesCelsius(double degreescelsius) -#else - public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) -#endif - { - double value = (double) degreescelsius; - return new Temperature(value, TemperatureUnit.DegreeCelsius); - } - - /// - /// Get Temperature from DegreesDelisle. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesDelisle(double degreesdelisle) -#else - public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) -#endif - { - double value = (double) degreesdelisle; - return new Temperature(value, TemperatureUnit.DegreeDelisle); - } - - /// - /// Get Temperature from DegreesFahrenheit. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesFahrenheit(double degreesfahrenheit) -#else - public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) -#endif - { - double value = (double) degreesfahrenheit; - return new Temperature(value, TemperatureUnit.DegreeFahrenheit); - } - - /// - /// Get Temperature from DegreesNewton. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesNewton(double degreesnewton) -#else - public static Temperature FromDegreesNewton(QuantityValue degreesnewton) -#endif - { - double value = (double) degreesnewton; - return new Temperature(value, TemperatureUnit.DegreeNewton); - } - - /// - /// Get Temperature from DegreesRankine. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesRankine(double degreesrankine) -#else - public static Temperature FromDegreesRankine(QuantityValue degreesrankine) -#endif - { - double value = (double) degreesrankine; - return new Temperature(value, TemperatureUnit.DegreeRankine); - } - - /// - /// Get Temperature from DegreesReaumur. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesReaumur(double degreesreaumur) -#else - public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) -#endif - { - double value = (double) degreesreaumur; - return new Temperature(value, TemperatureUnit.DegreeReaumur); - } - - /// - /// Get Temperature from DegreesRoemer. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesRoemer(double degreesroemer) -#else - public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) -#endif - { - double value = (double) degreesroemer; - return new Temperature(value, TemperatureUnit.DegreeRoemer); - } - - /// - /// Get Temperature from Kelvins. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromKelvins(double kelvins) -#else - public static Temperature FromKelvins(QuantityValue kelvins) -#endif - { - double value = (double) kelvins; - return new Temperature(value, TemperatureUnit.Kelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Temperature unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Temperature From(double value, TemperatureUnit fromUnit) -#else - public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) -#endif - { - return new Temperature((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Temperature)) throw new ArgumentException("Expected type Temperature.", nameof(obj)); - - return CompareTo((Temperature)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Temperature other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Temperature within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Temperature other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Temperature. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Temperature to another Temperature with the unit representation . - /// - /// A Temperature with the specified unit. - public Temperature ToUnit(TemperatureUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Temperature(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 AsBaseUnit() - { - switch(Unit) - { - case TemperatureUnit.DegreeCelsius: return _value + 273.15; - case TemperatureUnit.DegreeDelisle: return _value*-2/3 + 373.15; - case TemperatureUnit.DegreeFahrenheit: return _value*5/9 + 459.67*5/9; - case TemperatureUnit.DegreeNewton: return _value*100/33 + 273.15; - case TemperatureUnit.DegreeRankine: return _value*5/9; - case TemperatureUnit.DegreeReaumur: return _value*5/4 + 273.15; - case TemperatureUnit.DegreeRoemer: return _value*40/21 + 273.15 - 7.5*40d/21; - case TemperatureUnit.Kelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; - case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15)*-3/2; - case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67*5/9)*9/5; - case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15)*33/100; - case TemperatureUnit.DegreeRankine: return baseUnitValue*9/5; - case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15)*4/5; - case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5*40d/21))*21/40; - case TemperatureUnit.Kelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Temperature Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Temperature result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out TemperatureUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Temperature ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Temperature result) - { - result = default(Temperature); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static TemperatureUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == TemperatureUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out TemperatureUnit unit) - { - unit = TemperatureUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == TemperatureUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TemperatureUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Temperature - /// - public static Temperature MaxValue => new Temperature(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Temperature - /// - public static Temperature MinValue => new Temperature(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Temperature.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Temperature.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs b/Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs deleted file mode 100644 index 7fd42725ee..0000000000 --- a/Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs +++ /dev/null @@ -1,735 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class TemperatureChangeRate : IQuantity -#else - public partial struct TemperatureChangeRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureChangeRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static TemperatureChangeRate() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - TemperatureChangeRate(double numericValue, TemperatureChangeRateUnit unit) - { - if(unit == TemperatureChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.TemperatureChangeRate; - - /// - /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. - /// - public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the TemperatureChangeRate quantity. - /// - public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); - - /// - /// Get TemperatureChangeRate in CentidegreesCelsiusPerSecond. - /// - public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in DecadegreesCelsiusPerSecond. - /// - public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in DecidegreesCelsiusPerSecond. - /// - public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in DegreesCelsiusPerMinute. - /// - public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - - /// - /// Get TemperatureChangeRate in DegreesCelsiusPerSecond. - /// - public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in HectodegreesCelsiusPerSecond. - /// - public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in KilodegreesCelsiusPerSecond. - /// - public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in MicrodegreesCelsiusPerSecond. - /// - public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in MillidegreesCelsiusPerSecond. - /// - public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in NanodegreesCelsiusPerSecond. - /// - public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. - /// - public static TemperatureChangeRate Zero => new TemperatureChangeRate(0, BaseUnit); - - /// - /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double centidegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) -#endif - { - double value = (double) centidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double decadegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) -#endif - { - double value = (double) decadegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double decidegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) -#endif - { - double value = (double) decidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double degreescelsiusperminute) -#else - public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) -#endif - { - double value = (double) degreescelsiusperminute; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - } - - /// - /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double degreescelsiuspersecond) -#else - public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) -#endif - { - double value = (double) degreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double hectodegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) -#endif - { - double value = (double) hectodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double kilodegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) -#endif - { - double value = (double) kilodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double microdegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) -#endif - { - double value = (double) microdegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double millidegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) -#endif - { - double value = (double) millidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double nanodegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) -#endif - { - double value = (double) nanodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureChangeRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit fromUnit) -#else - public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) -#endif - { - return new TemperatureChangeRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is TemperatureChangeRate)) throw new ArgumentException("Expected type TemperatureChangeRate.", nameof(obj)); - - return CompareTo((TemperatureChangeRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(TemperatureChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another TemperatureChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureChangeRate. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureChangeRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . - /// - /// A TemperatureChangeRate with the specified unit. - public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureChangeRate(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 AsBaseUnit() - { - switch(Unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (_value) * 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (_value) * 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (_value) * 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return _value/60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return _value; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (_value) * 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (_value) * 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (_value) * 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (_value) * 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (_value) * 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureChangeRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (baseUnitValue) / 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return baseUnitValue*60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return baseUnitValue; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (baseUnitValue) / 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (baseUnitValue) / 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 TemperatureChangeRate Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureChangeRateUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static TemperatureChangeRate ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureChangeRate result) - { - result = default(TemperatureChangeRate); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static TemperatureChangeRateUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == TemperatureChangeRateUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out TemperatureChangeRateUnit unit) - { - unit = TemperatureChangeRateUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == TemperatureChangeRateUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TemperatureChangeRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of TemperatureChangeRate - /// - public static TemperatureChangeRate MaxValue => new TemperatureChangeRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of TemperatureChangeRate - /// - public static TemperatureChangeRate MinValue => new TemperatureChangeRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => TemperatureChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs b/Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs deleted file mode 100644 index 0cd1a49739..0000000000 --- a/Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs +++ /dev/null @@ -1,690 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Difference between two temperatures. The conversions are different than for Temperature. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class TemperatureDelta : IQuantity -#else - public partial struct TemperatureDelta : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureDeltaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static TemperatureDelta() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - TemperatureDelta(double numericValue, TemperatureDeltaUnit unit) - { - if(unit == TemperatureDeltaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.TemperatureDelta; - - /// - /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. - /// - public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the TemperatureDelta quantity. - /// - public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); - - /// - /// Get TemperatureDelta in DegreesCelsius. - /// - public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); - - /// - /// Get TemperatureDelta in DegreesDelisle. - /// - public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); - - /// - /// Get TemperatureDelta in DegreesFahrenheit. - /// - public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); - - /// - /// Get TemperatureDelta in DegreesNewton. - /// - public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); - - /// - /// Get TemperatureDelta in DegreesRankine. - /// - public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); - - /// - /// Get TemperatureDelta in DegreesReaumur. - /// - public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); - - /// - /// Get TemperatureDelta in DegreesRoemer. - /// - public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); - - /// - /// Get TemperatureDelta in Kelvins. - /// - public double Kelvins => As(TemperatureDeltaUnit.Kelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. - /// - public static TemperatureDelta Zero => new TemperatureDelta(0, BaseUnit); - - /// - /// Get TemperatureDelta from DegreesCelsius. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesCelsius(double degreescelsius) -#else - public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) -#endif - { - double value = (double) degreescelsius; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); - } - - /// - /// Get TemperatureDelta from DegreesDelisle. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesDelisle(double degreesdelisle) -#else - public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) -#endif - { - double value = (double) degreesdelisle; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); - } - - /// - /// Get TemperatureDelta from DegreesFahrenheit. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesFahrenheit(double degreesfahrenheit) -#else - public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) -#endif - { - double value = (double) degreesfahrenheit; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); - } - - /// - /// Get TemperatureDelta from DegreesNewton. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesNewton(double degreesnewton) -#else - public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) -#endif - { - double value = (double) degreesnewton; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); - } - - /// - /// Get TemperatureDelta from DegreesRankine. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRankine(double degreesrankine) -#else - public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) -#endif - { - double value = (double) degreesrankine; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); - } - - /// - /// Get TemperatureDelta from DegreesReaumur. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesReaumur(double degreesreaumur) -#else - public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) -#endif - { - double value = (double) degreesreaumur; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); - } - - /// - /// Get TemperatureDelta from DegreesRoemer. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRoemer(double degreesroemer) -#else - public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) -#endif - { - double value = (double) degreesroemer; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); - } - - /// - /// Get TemperatureDelta from Kelvins. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromKelvins(double kelvins) -#else - public static TemperatureDelta FromKelvins(QuantityValue kelvins) -#endif - { - double value = (double) kelvins; - return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureDelta unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) -#else - public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) -#endif - { - return new TemperatureDelta((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureDeltaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is TemperatureDelta)) throw new ArgumentException("Expected type TemperatureDelta.", nameof(obj)); - - return CompareTo((TemperatureDelta)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(TemperatureDelta other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another TemperatureDelta within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureDelta. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureDeltaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation . - /// - /// A TemperatureDelta with the specified unit. - public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureDelta(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 AsBaseUnit() - { - switch(Unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return _value; - case TemperatureDeltaUnit.DegreeDelisle: return _value*-2/3; - case TemperatureDeltaUnit.DegreeFahrenheit: return _value*5/9; - case TemperatureDeltaUnit.DegreeNewton: return _value*100/33; - case TemperatureDeltaUnit.DegreeRankine: return _value*5/9; - case TemperatureDeltaUnit.DegreeReaumur: return _value*5/4; - case TemperatureDeltaUnit.DegreeRoemer: return _value*40/21; - case TemperatureDeltaUnit.Kelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureDeltaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; - case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue*-3/2; - case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue*33/100; - case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue*4/5; - case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue*21/40; - case TemperatureDeltaUnit.Kelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 TemperatureDelta Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureDelta result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureDeltaUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static TemperatureDelta ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureDelta result) - { - result = default(TemperatureDelta); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static TemperatureDeltaUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == TemperatureDeltaUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureDeltaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out TemperatureDeltaUnit unit) - { - unit = TemperatureDeltaUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == TemperatureDeltaUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TemperatureDeltaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of TemperatureDelta - /// - public static TemperatureDelta MaxValue => new TemperatureDelta(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of TemperatureDelta - /// - public static TemperatureDelta MinValue => new TemperatureDelta(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => TemperatureDelta.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs b/Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs deleted file mode 100644 index 1c23b158ee..0000000000 --- a/Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs +++ /dev/null @@ -1,559 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Thermal conductivity is the property of a material to conduct heat. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ThermalConductivity : IQuantity -#else - public partial struct ThermalConductivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ThermalConductivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ThermalConductivity() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ThermalConductivity(double numericValue, ThermalConductivityUnit unit) - { - if(unit == ThermalConductivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ThermalConductivity; - - /// - /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. - /// - public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ThermalConductivity quantity. - /// - public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); - - /// - /// Get ThermalConductivity in BtusPerHourFootFahrenheit. - /// - public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); - - /// - /// Get ThermalConductivity in WattsPerMeterKelvin. - /// - public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. - /// - public static ThermalConductivity Zero => new ThermalConductivity(0, BaseUnit); - - /// - /// Get ThermalConductivity from BtusPerHourFootFahrenheit. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalConductivity FromBtusPerHourFootFahrenheit(double btusperhourfootfahrenheit) -#else - public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue btusperhourfootfahrenheit) -#endif - { - double value = (double) btusperhourfootfahrenheit; - return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); - } - - /// - /// Get ThermalConductivity from WattsPerMeterKelvin. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalConductivity FromWattsPerMeterKelvin(double wattspermeterkelvin) -#else - public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) -#endif - { - double value = (double) wattspermeterkelvin; - return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ThermalConductivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ThermalConductivity From(double value, ThermalConductivityUnit fromUnit) -#else - public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) -#endif - { - return new ThermalConductivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ThermalConductivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ThermalConductivity)) throw new ArgumentException("Expected type ThermalConductivity.", nameof(obj)); - - return CompareTo((ThermalConductivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ThermalConductivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ThermalConductivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ThermalConductivity other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalConductivity. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalConductivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . - /// - /// A ThermalConductivity with the specified unit. - public ThermalConductivity ToUnit(ThermalConductivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ThermalConductivity(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 AsBaseUnit() - { - switch(Unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return _value*1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ThermalConductivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return baseUnitValue/1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ThermalConductivity Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ThermalConductivity result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalConductivityUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ThermalConductivity ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ThermalConductivity result) - { - result = default(ThermalConductivity); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ThermalConductivityUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ThermalConductivityUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalConductivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ThermalConductivityUnit unit) - { - unit = ThermalConductivityUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ThermalConductivityUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ThermalConductivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ThermalConductivity - /// - public static ThermalConductivity MaxValue => new ThermalConductivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ThermalConductivity - /// - public static ThermalConductivity MinValue => new ThermalConductivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ThermalConductivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs b/Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs deleted file mode 100644 index a50ef603b4..0000000000 --- a/Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs +++ /dev/null @@ -1,625 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ThermalResistance : IQuantity -#else - public partial struct ThermalResistance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ThermalResistanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ThermalResistance() - { - BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - ThermalResistance(double numericValue, ThermalResistanceUnit unit) - { - if(unit == ThermalResistanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ThermalResistance; - - /// - /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. - /// - public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ThermalResistance quantity. - /// - public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); - - /// - /// Get ThermalResistance in HourSquareFeetDegreesFahrenheitPerBtu. - /// - public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - - /// - /// Get ThermalResistance in SquareCentimeterHourDegreesCelsiusPerKilocalorie. - /// - public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - - /// - /// Get ThermalResistance in SquareCentimeterKelvinsPerWatt. - /// - public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - - /// - /// Get ThermalResistance in SquareMeterDegreesCelsiusPerWatt. - /// - public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - - /// - /// Get ThermalResistance in SquareMeterKelvinsPerKilowatt. - /// - public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. - /// - public static ThermalResistance Zero => new ThermalResistance(0, BaseUnit); - - /// - /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(double hoursquarefeetdegreesfahrenheitperbtu) -#else - public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) -#endif - { - double value = (double) hoursquarefeetdegreesfahrenheitperbtu; - return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - } - - /// - /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double squarecentimeterhourdegreescelsiusperkilocalorie) -#else - public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) -#endif - { - double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; - return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - } - - /// - /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(double squarecentimeterkelvinsperwatt) -#else - public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) -#endif - { - double value = (double) squarecentimeterkelvinsperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - } - - /// - /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(double squaremeterdegreescelsiusperwatt) -#else - public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) -#endif - { - double value = (double) squaremeterdegreescelsiusperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - } - - /// - /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(double squaremeterkelvinsperkilowatt) -#else - public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) -#endif - { - double value = (double) squaremeterkelvinsperkilowatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ThermalResistance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ThermalResistance From(double value, ThermalResistanceUnit fromUnit) -#else - public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) -#endif - { - return new ThermalResistance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ThermalResistanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ThermalResistance)) throw new ArgumentException("Expected type ThermalResistance.", nameof(obj)); - - return CompareTo((ThermalResistance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ThermalResistance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ThermalResistance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ThermalResistance other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalResistance. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalResistanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ThermalResistance to another ThermalResistance with the unit representation . - /// - /// A ThermalResistance with the specified unit. - public ThermalResistance ToUnit(ThermalResistanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ThermalResistance(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 AsBaseUnit() - { - switch(Unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value*176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value*0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value*0.0999964777570357; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value*1000.088056074108; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ThermalResistanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue/176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue/0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue/0.0999964777570357; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue/1000.088056074108; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 ThermalResistance Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ThermalResistance result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalResistanceUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static ThermalResistance ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ThermalResistance result) - { - result = default(ThermalResistance); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static ThermalResistanceUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == ThermalResistanceUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalResistanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out ThermalResistanceUnit unit) - { - unit = ThermalResistanceUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == ThermalResistanceUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ThermalResistanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ThermalResistance - /// - public static ThermalResistance MaxValue => new ThermalResistance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ThermalResistance - /// - public static ThermalResistance MinValue => new ThermalResistance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ThermalResistance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Torque.Common.g.cs b/Common/GeneratedCode/Quantities/Torque.Common.g.cs deleted file mode 100644 index fd91c3cca3..0000000000 --- a/Common/GeneratedCode/Quantities/Torque.Common.g.cs +++ /dev/null @@ -1,977 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Torque : IQuantity -#else - public partial struct Torque : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TorqueUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Torque() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Torque(double numericValue, TorqueUnit unit) - { - if(unit == TorqueUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Torque; - - /// - /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. - /// - public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Torque quantity. - /// - public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); - - /// - /// Get Torque in KilogramForceCentimeters. - /// - public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); - - /// - /// Get Torque in KilogramForceMeters. - /// - public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); - - /// - /// Get Torque in KilogramForceMillimeters. - /// - public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); - - /// - /// Get Torque in KilonewtonCentimeters. - /// - public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); - - /// - /// Get Torque in KilonewtonMeters. - /// - public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); - - /// - /// Get Torque in KilonewtonMillimeters. - /// - public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); - - /// - /// Get Torque in KilopoundForceFeet. - /// - public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); - - /// - /// Get Torque in KilopoundForceInches. - /// - public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); - - /// - /// Get Torque in MeganewtonCentimeters. - /// - public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); - - /// - /// Get Torque in MeganewtonMeters. - /// - public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); - - /// - /// Get Torque in MeganewtonMillimeters. - /// - public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); - - /// - /// Get Torque in MegapoundForceFeet. - /// - public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); - - /// - /// Get Torque in MegapoundForceInches. - /// - public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); - - /// - /// Get Torque in NewtonCentimeters. - /// - public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); - - /// - /// Get Torque in NewtonMeters. - /// - public double NewtonMeters => As(TorqueUnit.NewtonMeter); - - /// - /// Get Torque in NewtonMillimeters. - /// - public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); - - /// - /// Get Torque in PoundForceFeet. - /// - public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); - - /// - /// Get Torque in PoundForceInches. - /// - public double PoundForceInches => As(TorqueUnit.PoundForceInch); - - /// - /// Get Torque in TonneForceCentimeters. - /// - public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); - - /// - /// Get Torque in TonneForceMeters. - /// - public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); - - /// - /// Get Torque in TonneForceMillimeters. - /// - public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. - /// - public static Torque Zero => new Torque(0, BaseUnit); - - /// - /// Get Torque from KilogramForceCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceCentimeters(double kilogramforcecentimeters) -#else - public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) -#endif - { - double value = (double) kilogramforcecentimeters; - return new Torque(value, TorqueUnit.KilogramForceCentimeter); - } - - /// - /// Get Torque from KilogramForceMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceMeters(double kilogramforcemeters) -#else - public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) -#endif - { - double value = (double) kilogramforcemeters; - return new Torque(value, TorqueUnit.KilogramForceMeter); - } - - /// - /// Get Torque from KilogramForceMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceMillimeters(double kilogramforcemillimeters) -#else - public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) -#endif - { - double value = (double) kilogramforcemillimeters; - return new Torque(value, TorqueUnit.KilogramForceMillimeter); - } - - /// - /// Get Torque from KilonewtonCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonCentimeters(double kilonewtoncentimeters) -#else - public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) -#endif - { - double value = (double) kilonewtoncentimeters; - return new Torque(value, TorqueUnit.KilonewtonCentimeter); - } - - /// - /// Get Torque from KilonewtonMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonMeters(double kilonewtonmeters) -#else - public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) -#endif - { - double value = (double) kilonewtonmeters; - return new Torque(value, TorqueUnit.KilonewtonMeter); - } - - /// - /// Get Torque from KilonewtonMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonMillimeters(double kilonewtonmillimeters) -#else - public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) -#endif - { - double value = (double) kilonewtonmillimeters; - return new Torque(value, TorqueUnit.KilonewtonMillimeter); - } - - /// - /// Get Torque from KilopoundForceFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilopoundForceFeet(double kilopoundforcefeet) -#else - public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) -#endif - { - double value = (double) kilopoundforcefeet; - return new Torque(value, TorqueUnit.KilopoundForceFoot); - } - - /// - /// Get Torque from KilopoundForceInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilopoundForceInches(double kilopoundforceinches) -#else - public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) -#endif - { - double value = (double) kilopoundforceinches; - return new Torque(value, TorqueUnit.KilopoundForceInch); - } - - /// - /// Get Torque from MeganewtonCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonCentimeters(double meganewtoncentimeters) -#else - public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) -#endif - { - double value = (double) meganewtoncentimeters; - return new Torque(value, TorqueUnit.MeganewtonCentimeter); - } - - /// - /// Get Torque from MeganewtonMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonMeters(double meganewtonmeters) -#else - public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) -#endif - { - double value = (double) meganewtonmeters; - return new Torque(value, TorqueUnit.MeganewtonMeter); - } - - /// - /// Get Torque from MeganewtonMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonMillimeters(double meganewtonmillimeters) -#else - public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) -#endif - { - double value = (double) meganewtonmillimeters; - return new Torque(value, TorqueUnit.MeganewtonMillimeter); - } - - /// - /// Get Torque from MegapoundForceFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMegapoundForceFeet(double megapoundforcefeet) -#else - public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) -#endif - { - double value = (double) megapoundforcefeet; - return new Torque(value, TorqueUnit.MegapoundForceFoot); - } - - /// - /// Get Torque from MegapoundForceInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMegapoundForceInches(double megapoundforceinches) -#else - public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) -#endif - { - double value = (double) megapoundforceinches; - return new Torque(value, TorqueUnit.MegapoundForceInch); - } - - /// - /// Get Torque from NewtonCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonCentimeters(double newtoncentimeters) -#else - public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) -#endif - { - double value = (double) newtoncentimeters; - return new Torque(value, TorqueUnit.NewtonCentimeter); - } - - /// - /// Get Torque from NewtonMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonMeters(double newtonmeters) -#else - public static Torque FromNewtonMeters(QuantityValue newtonmeters) -#endif - { - double value = (double) newtonmeters; - return new Torque(value, TorqueUnit.NewtonMeter); - } - - /// - /// Get Torque from NewtonMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonMillimeters(double newtonmillimeters) -#else - public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) -#endif - { - double value = (double) newtonmillimeters; - return new Torque(value, TorqueUnit.NewtonMillimeter); - } - - /// - /// Get Torque from PoundForceFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundForceFeet(double poundforcefeet) -#else - public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) -#endif - { - double value = (double) poundforcefeet; - return new Torque(value, TorqueUnit.PoundForceFoot); - } - - /// - /// Get Torque from PoundForceInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundForceInches(double poundforceinches) -#else - public static Torque FromPoundForceInches(QuantityValue poundforceinches) -#endif - { - double value = (double) poundforceinches; - return new Torque(value, TorqueUnit.PoundForceInch); - } - - /// - /// Get Torque from TonneForceCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceCentimeters(double tonneforcecentimeters) -#else - public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) -#endif - { - double value = (double) tonneforcecentimeters; - return new Torque(value, TorqueUnit.TonneForceCentimeter); - } - - /// - /// Get Torque from TonneForceMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceMeters(double tonneforcemeters) -#else - public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) -#endif - { - double value = (double) tonneforcemeters; - return new Torque(value, TorqueUnit.TonneForceMeter); - } - - /// - /// Get Torque from TonneForceMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceMillimeters(double tonneforcemillimeters) -#else - public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) -#endif - { - double value = (double) tonneforcemillimeters; - return new Torque(value, TorqueUnit.TonneForceMillimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Torque unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Torque From(double value, TorqueUnit fromUnit) -#else - public static Torque From(QuantityValue value, TorqueUnit fromUnit) -#endif - { - return new Torque((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TorqueUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Torque)) throw new ArgumentException("Expected type Torque.", nameof(obj)); - - return CompareTo((Torque)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Torque other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Torque within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Torque other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Torque. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorqueUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Torque to another Torque with the unit representation . - /// - /// A Torque with the specified unit. - public Torque ToUnit(TorqueUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Torque(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 AsBaseUnit() - { - switch(Unit) - { - case TorqueUnit.KilogramForceCentimeter: return _value*0.0980665019960652; - case TorqueUnit.KilogramForceMeter: return _value*9.80665019960652; - case TorqueUnit.KilogramForceMillimeter: return _value*0.00980665019960652; - case TorqueUnit.KilonewtonCentimeter: return (_value*0.01) * 1e3d; - case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (_value*0.001) * 1e3d; - case TorqueUnit.KilopoundForceFoot: return (_value*1.3558179483314) * 1e3d; - case TorqueUnit.KilopoundForceInch: return (_value*1.129848290276167e-1) * 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (_value*0.01) * 1e6d; - case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (_value*0.001) * 1e6d; - case TorqueUnit.MegapoundForceFoot: return (_value*1.3558179483314) * 1e6d; - case TorqueUnit.MegapoundForceInch: return (_value*1.129848290276167e-1) * 1e6d; - case TorqueUnit.NewtonCentimeter: return _value*0.01; - case TorqueUnit.NewtonMeter: return _value; - case TorqueUnit.NewtonMillimeter: return _value*0.001; - case TorqueUnit.PoundForceFoot: return _value*1.3558179483314; - case TorqueUnit.PoundForceInch: return _value*1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return _value*98.0665019960652; - case TorqueUnit.TonneForceMeter: return _value*9806.65019960653; - case TorqueUnit.TonneForceMillimeter: return _value*9.80665019960652; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TorqueUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TorqueUnit.KilogramForceCentimeter: return baseUnitValue*10.1971619222242; - case TorqueUnit.KilogramForceMeter: return baseUnitValue*0.101971619222242; - case TorqueUnit.KilogramForceMillimeter: return baseUnitValue*101.971619222242; - case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue*100) / 1e3d; - case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue*1000) / 1e3d; - case TorqueUnit.KilopoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e3d; - case TorqueUnit.KilopoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue*100) / 1e6d; - case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue*1000) / 1e6d; - case TorqueUnit.MegapoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e6d; - case TorqueUnit.MegapoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e6d; - case TorqueUnit.NewtonCentimeter: return baseUnitValue*100; - case TorqueUnit.NewtonMeter: return baseUnitValue; - case TorqueUnit.NewtonMillimeter: return baseUnitValue*1000; - case TorqueUnit.PoundForceFoot: return baseUnitValue/1.3558179483314; - case TorqueUnit.PoundForceInch: return baseUnitValue/1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return baseUnitValue*0.0101971619222242; - case TorqueUnit.TonneForceMeter: return baseUnitValue*0.000101971619222242; - case TorqueUnit.TonneForceMillimeter: return baseUnitValue*0.101971619222242; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Torque Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Torque result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TorqueUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out TorqueUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Torque ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Torque result) - { - result = default(Torque); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static TorqueUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == TorqueUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TorqueUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out TorqueUnit unit) - { - unit = TorqueUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == TorqueUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TorqueUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Torque - /// - public static Torque MaxValue => new Torque(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Torque - /// - public static Torque MinValue => new Torque(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Torque.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Torque.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/VitaminA.Common.g.cs b/Common/GeneratedCode/Quantities/VitaminA.Common.g.cs deleted file mode 100644 index cbf92fdf97..0000000000 --- a/Common/GeneratedCode/Quantities/VitaminA.Common.g.cs +++ /dev/null @@ -1,536 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class VitaminA : IQuantity -#else - public partial struct VitaminA : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VitaminAUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static VitaminA() - { - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - VitaminA(double numericValue, VitaminAUnit unit) - { - if(unit == VitaminAUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.VitaminA; - - /// - /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. - /// - public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the VitaminA quantity. - /// - public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); - - /// - /// Get VitaminA in InternationalUnits. - /// - public double InternationalUnits => As(VitaminAUnit.InternationalUnit); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. - /// - public static VitaminA Zero => new VitaminA(0, BaseUnit); - - /// - /// Get VitaminA from InternationalUnits. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VitaminA FromInternationalUnits(double internationalunits) -#else - public static VitaminA FromInternationalUnits(QuantityValue internationalunits) -#endif - { - double value = (double) internationalunits; - return new VitaminA(value, VitaminAUnit.InternationalUnit); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VitaminA unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VitaminA From(double value, VitaminAUnit fromUnit) -#else - public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) -#endif - { - return new VitaminA((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VitaminAUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is VitaminA)) throw new ArgumentException("Expected type VitaminA.", nameof(obj)); - - return CompareTo((VitaminA)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(VitaminA other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VitaminA within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VitaminA. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VitaminAUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VitaminA to another VitaminA with the unit representation . - /// - /// A VitaminA with the specified unit. - public VitaminA ToUnit(VitaminAUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VitaminA(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 AsBaseUnit() - { - switch(Unit) - { - case VitaminAUnit.InternationalUnit: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VitaminAUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VitaminAUnit.InternationalUnit: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 VitaminA Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VitaminA result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VitaminAUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out VitaminAUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static VitaminA ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out VitaminA result) - { - result = default(VitaminA); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static VitaminAUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == VitaminAUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VitaminAUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out VitaminAUnit unit) - { - unit = VitaminAUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == VitaminAUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(VitaminAUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of VitaminA - /// - public static VitaminA MaxValue => new VitaminA(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of VitaminA - /// - public static VitaminA MinValue => new VitaminA(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => VitaminA.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VitaminA.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Volume.Common.g.cs b/Common/GeneratedCode/Quantities/Volume.Common.g.cs deleted file mode 100644 index be78c8f41e..0000000000 --- a/Common/GeneratedCode/Quantities/Volume.Common.g.cs +++ /dev/null @@ -1,1439 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Volume : IQuantity -#else - public partial struct Volume : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Volume() - { - BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - Volume(double numericValue, VolumeUnit unit) - { - if(unit == VolumeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Volume; - - /// - /// The base unit of Volume, which is CubicMeter. All conversions go via this value. - /// - public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Volume quantity. - /// - public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); - - /// - /// Get Volume in AuTablespoons. - /// - public double AuTablespoons => As(VolumeUnit.AuTablespoon); - - /// - /// Get Volume in Centiliters. - /// - public double Centiliters => As(VolumeUnit.Centiliter); - - /// - /// Get Volume in CubicCentimeters. - /// - public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); - - /// - /// Get Volume in CubicDecimeters. - /// - public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); - - /// - /// Get Volume in CubicFeet. - /// - public double CubicFeet => As(VolumeUnit.CubicFoot); - - /// - /// Get Volume in CubicInches. - /// - public double CubicInches => As(VolumeUnit.CubicInch); - - /// - /// Get Volume in CubicKilometers. - /// - public double CubicKilometers => As(VolumeUnit.CubicKilometer); - - /// - /// Get Volume in CubicMeters. - /// - public double CubicMeters => As(VolumeUnit.CubicMeter); - - /// - /// Get Volume in CubicMicrometers. - /// - public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); - - /// - /// Get Volume in CubicMiles. - /// - public double CubicMiles => As(VolumeUnit.CubicMile); - - /// - /// Get Volume in CubicMillimeters. - /// - public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); - - /// - /// Get Volume in CubicYards. - /// - public double CubicYards => As(VolumeUnit.CubicYard); - - /// - /// Get Volume in Deciliters. - /// - public double Deciliters => As(VolumeUnit.Deciliter); - - /// - /// Get Volume in HectocubicFeet. - /// - public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); - - /// - /// Get Volume in HectocubicMeters. - /// - public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); - - /// - /// Get Volume in Hectoliters. - /// - public double Hectoliters => As(VolumeUnit.Hectoliter); - - /// - /// Get Volume in ImperialBeerBarrels. - /// - public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); - - /// - /// Get Volume in ImperialGallons. - /// - public double ImperialGallons => As(VolumeUnit.ImperialGallon); - - /// - /// Get Volume in ImperialOunces. - /// - public double ImperialOunces => As(VolumeUnit.ImperialOunce); - - /// - /// Get Volume in KilocubicFeet. - /// - public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); - - /// - /// Get Volume in KilocubicMeters. - /// - public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); - - /// - /// Get Volume in KiloimperialGallons. - /// - public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); - - /// - /// Get Volume in KilousGallons. - /// - public double KilousGallons => As(VolumeUnit.KilousGallon); - - /// - /// Get Volume in Liters. - /// - public double Liters => As(VolumeUnit.Liter); - - /// - /// Get Volume in MegacubicFeet. - /// - public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); - - /// - /// Get Volume in MegaimperialGallons. - /// - public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); - - /// - /// Get Volume in MegausGallons. - /// - public double MegausGallons => As(VolumeUnit.MegausGallon); - - /// - /// Get Volume in MetricCups. - /// - public double MetricCups => As(VolumeUnit.MetricCup); - - /// - /// Get Volume in MetricTeaspoons. - /// - public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); - - /// - /// Get Volume in Microliters. - /// - public double Microliters => As(VolumeUnit.Microliter); - - /// - /// Get Volume in Milliliters. - /// - public double Milliliters => As(VolumeUnit.Milliliter); - - /// - /// Get Volume in OilBarrels. - /// - public double OilBarrels => As(VolumeUnit.OilBarrel); - - /// - /// Get Volume in UkTablespoons. - /// - public double UkTablespoons => As(VolumeUnit.UkTablespoon); - - /// - /// Get Volume in UsBeerBarrels. - /// - public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); - - /// - /// Get Volume in UsCustomaryCups. - /// - public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); - - /// - /// Get Volume in UsGallons. - /// - public double UsGallons => As(VolumeUnit.UsGallon); - - /// - /// Get Volume in UsLegalCups. - /// - public double UsLegalCups => As(VolumeUnit.UsLegalCup); - - /// - /// Get Volume in UsOunces. - /// - public double UsOunces => As(VolumeUnit.UsOunce); - - /// - /// Get Volume in UsPints. - /// - public double UsPints => As(VolumeUnit.UsPint); - - /// - /// Get Volume in UsQuarts. - /// - public double UsQuarts => As(VolumeUnit.UsQuart); - - /// - /// Get Volume in UsTablespoons. - /// - public double UsTablespoons => As(VolumeUnit.UsTablespoon); - - /// - /// Get Volume in UsTeaspoons. - /// - public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. - /// - public static Volume Zero => new Volume(0, BaseUnit); - - /// - /// Get Volume from AuTablespoons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromAuTablespoons(double autablespoons) -#else - public static Volume FromAuTablespoons(QuantityValue autablespoons) -#endif - { - double value = (double) autablespoons; - return new Volume(value, VolumeUnit.AuTablespoon); - } - - /// - /// Get Volume from Centiliters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCentiliters(double centiliters) -#else - public static Volume FromCentiliters(QuantityValue centiliters) -#endif - { - double value = (double) centiliters; - return new Volume(value, VolumeUnit.Centiliter); - } - - /// - /// Get Volume from CubicCentimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicCentimeters(double cubiccentimeters) -#else - public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) -#endif - { - double value = (double) cubiccentimeters; - return new Volume(value, VolumeUnit.CubicCentimeter); - } - - /// - /// Get Volume from CubicDecimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicDecimeters(double cubicdecimeters) -#else - public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) -#endif - { - double value = (double) cubicdecimeters; - return new Volume(value, VolumeUnit.CubicDecimeter); - } - - /// - /// Get Volume from CubicFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicFeet(double cubicfeet) -#else - public static Volume FromCubicFeet(QuantityValue cubicfeet) -#endif - { - double value = (double) cubicfeet; - return new Volume(value, VolumeUnit.CubicFoot); - } - - /// - /// Get Volume from CubicInches. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicInches(double cubicinches) -#else - public static Volume FromCubicInches(QuantityValue cubicinches) -#endif - { - double value = (double) cubicinches; - return new Volume(value, VolumeUnit.CubicInch); - } - - /// - /// Get Volume from CubicKilometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicKilometers(double cubickilometers) -#else - public static Volume FromCubicKilometers(QuantityValue cubickilometers) -#endif - { - double value = (double) cubickilometers; - return new Volume(value, VolumeUnit.CubicKilometer); - } - - /// - /// Get Volume from CubicMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMeters(double cubicmeters) -#else - public static Volume FromCubicMeters(QuantityValue cubicmeters) -#endif - { - double value = (double) cubicmeters; - return new Volume(value, VolumeUnit.CubicMeter); - } - - /// - /// Get Volume from CubicMicrometers. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMicrometers(double cubicmicrometers) -#else - public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) -#endif - { - double value = (double) cubicmicrometers; - return new Volume(value, VolumeUnit.CubicMicrometer); - } - - /// - /// Get Volume from CubicMiles. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMiles(double cubicmiles) -#else - public static Volume FromCubicMiles(QuantityValue cubicmiles) -#endif - { - double value = (double) cubicmiles; - return new Volume(value, VolumeUnit.CubicMile); - } - - /// - /// Get Volume from CubicMillimeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMillimeters(double cubicmillimeters) -#else - public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) -#endif - { - double value = (double) cubicmillimeters; - return new Volume(value, VolumeUnit.CubicMillimeter); - } - - /// - /// Get Volume from CubicYards. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicYards(double cubicyards) -#else - public static Volume FromCubicYards(QuantityValue cubicyards) -#endif - { - double value = (double) cubicyards; - return new Volume(value, VolumeUnit.CubicYard); - } - - /// - /// Get Volume from Deciliters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromDeciliters(double deciliters) -#else - public static Volume FromDeciliters(QuantityValue deciliters) -#endif - { - double value = (double) deciliters; - return new Volume(value, VolumeUnit.Deciliter); - } - - /// - /// Get Volume from HectocubicFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectocubicFeet(double hectocubicfeet) -#else - public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) -#endif - { - double value = (double) hectocubicfeet; - return new Volume(value, VolumeUnit.HectocubicFoot); - } - - /// - /// Get Volume from HectocubicMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectocubicMeters(double hectocubicmeters) -#else - public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) -#endif - { - double value = (double) hectocubicmeters; - return new Volume(value, VolumeUnit.HectocubicMeter); - } - - /// - /// Get Volume from Hectoliters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectoliters(double hectoliters) -#else - public static Volume FromHectoliters(QuantityValue hectoliters) -#endif - { - double value = (double) hectoliters; - return new Volume(value, VolumeUnit.Hectoliter); - } - - /// - /// Get Volume from ImperialBeerBarrels. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialBeerBarrels(double imperialbeerbarrels) -#else - public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) -#endif - { - double value = (double) imperialbeerbarrels; - return new Volume(value, VolumeUnit.ImperialBeerBarrel); - } - - /// - /// Get Volume from ImperialGallons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialGallons(double imperialgallons) -#else - public static Volume FromImperialGallons(QuantityValue imperialgallons) -#endif - { - double value = (double) imperialgallons; - return new Volume(value, VolumeUnit.ImperialGallon); - } - - /// - /// Get Volume from ImperialOunces. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialOunces(double imperialounces) -#else - public static Volume FromImperialOunces(QuantityValue imperialounces) -#endif - { - double value = (double) imperialounces; - return new Volume(value, VolumeUnit.ImperialOunce); - } - - /// - /// Get Volume from KilocubicFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilocubicFeet(double kilocubicfeet) -#else - public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) -#endif - { - double value = (double) kilocubicfeet; - return new Volume(value, VolumeUnit.KilocubicFoot); - } - - /// - /// Get Volume from KilocubicMeters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilocubicMeters(double kilocubicmeters) -#else - public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) -#endif - { - double value = (double) kilocubicmeters; - return new Volume(value, VolumeUnit.KilocubicMeter); - } - - /// - /// Get Volume from KiloimperialGallons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKiloimperialGallons(double kiloimperialgallons) -#else - public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) -#endif - { - double value = (double) kiloimperialgallons; - return new Volume(value, VolumeUnit.KiloimperialGallon); - } - - /// - /// Get Volume from KilousGallons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilousGallons(double kilousgallons) -#else - public static Volume FromKilousGallons(QuantityValue kilousgallons) -#endif - { - double value = (double) kilousgallons; - return new Volume(value, VolumeUnit.KilousGallon); - } - - /// - /// Get Volume from Liters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromLiters(double liters) -#else - public static Volume FromLiters(QuantityValue liters) -#endif - { - double value = (double) liters; - return new Volume(value, VolumeUnit.Liter); - } - - /// - /// Get Volume from MegacubicFeet. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegacubicFeet(double megacubicfeet) -#else - public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) -#endif - { - double value = (double) megacubicfeet; - return new Volume(value, VolumeUnit.MegacubicFoot); - } - - /// - /// Get Volume from MegaimperialGallons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegaimperialGallons(double megaimperialgallons) -#else - public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) -#endif - { - double value = (double) megaimperialgallons; - return new Volume(value, VolumeUnit.MegaimperialGallon); - } - - /// - /// Get Volume from MegausGallons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegausGallons(double megausgallons) -#else - public static Volume FromMegausGallons(QuantityValue megausgallons) -#endif - { - double value = (double) megausgallons; - return new Volume(value, VolumeUnit.MegausGallon); - } - - /// - /// Get Volume from MetricCups. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMetricCups(double metriccups) -#else - public static Volume FromMetricCups(QuantityValue metriccups) -#endif - { - double value = (double) metriccups; - return new Volume(value, VolumeUnit.MetricCup); - } - - /// - /// Get Volume from MetricTeaspoons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMetricTeaspoons(double metricteaspoons) -#else - public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) -#endif - { - double value = (double) metricteaspoons; - return new Volume(value, VolumeUnit.MetricTeaspoon); - } - - /// - /// Get Volume from Microliters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMicroliters(double microliters) -#else - public static Volume FromMicroliters(QuantityValue microliters) -#endif - { - double value = (double) microliters; - return new Volume(value, VolumeUnit.Microliter); - } - - /// - /// Get Volume from Milliliters. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMilliliters(double milliliters) -#else - public static Volume FromMilliliters(QuantityValue milliliters) -#endif - { - double value = (double) milliliters; - return new Volume(value, VolumeUnit.Milliliter); - } - - /// - /// Get Volume from OilBarrels. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromOilBarrels(double oilbarrels) -#else - public static Volume FromOilBarrels(QuantityValue oilbarrels) -#endif - { - double value = (double) oilbarrels; - return new Volume(value, VolumeUnit.OilBarrel); - } - - /// - /// Get Volume from UkTablespoons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUkTablespoons(double uktablespoons) -#else - public static Volume FromUkTablespoons(QuantityValue uktablespoons) -#endif - { - double value = (double) uktablespoons; - return new Volume(value, VolumeUnit.UkTablespoon); - } - - /// - /// Get Volume from UsBeerBarrels. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsBeerBarrels(double usbeerbarrels) -#else - public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) -#endif - { - double value = (double) usbeerbarrels; - return new Volume(value, VolumeUnit.UsBeerBarrel); - } - - /// - /// Get Volume from UsCustomaryCups. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsCustomaryCups(double uscustomarycups) -#else - public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) -#endif - { - double value = (double) uscustomarycups; - return new Volume(value, VolumeUnit.UsCustomaryCup); - } - - /// - /// Get Volume from UsGallons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsGallons(double usgallons) -#else - public static Volume FromUsGallons(QuantityValue usgallons) -#endif - { - double value = (double) usgallons; - return new Volume(value, VolumeUnit.UsGallon); - } - - /// - /// Get Volume from UsLegalCups. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsLegalCups(double uslegalcups) -#else - public static Volume FromUsLegalCups(QuantityValue uslegalcups) -#endif - { - double value = (double) uslegalcups; - return new Volume(value, VolumeUnit.UsLegalCup); - } - - /// - /// Get Volume from UsOunces. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsOunces(double usounces) -#else - public static Volume FromUsOunces(QuantityValue usounces) -#endif - { - double value = (double) usounces; - return new Volume(value, VolumeUnit.UsOunce); - } - - /// - /// Get Volume from UsPints. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsPints(double uspints) -#else - public static Volume FromUsPints(QuantityValue uspints) -#endif - { - double value = (double) uspints; - return new Volume(value, VolumeUnit.UsPint); - } - - /// - /// Get Volume from UsQuarts. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsQuarts(double usquarts) -#else - public static Volume FromUsQuarts(QuantityValue usquarts) -#endif - { - double value = (double) usquarts; - return new Volume(value, VolumeUnit.UsQuart); - } - - /// - /// Get Volume from UsTablespoons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsTablespoons(double ustablespoons) -#else - public static Volume FromUsTablespoons(QuantityValue ustablespoons) -#endif - { - double value = (double) ustablespoons; - return new Volume(value, VolumeUnit.UsTablespoon); - } - - /// - /// Get Volume from UsTeaspoons. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsTeaspoons(double usteaspoons) -#else - public static Volume FromUsTeaspoons(QuantityValue usteaspoons) -#endif - { - double value = (double) usteaspoons; - return new Volume(value, VolumeUnit.UsTeaspoon); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Volume unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Volume From(double value, VolumeUnit fromUnit) -#else - public static Volume From(QuantityValue value, VolumeUnit fromUnit) -#endif - { - return new Volume((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VolumeUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Volume)) throw new ArgumentException("Expected type Volume.", nameof(obj)); - - return CompareTo((Volume)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Volume other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Volume within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Volume other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Volume. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Volume to another Volume with the unit representation . - /// - /// A Volume with the specified unit. - public Volume ToUnit(VolumeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Volume(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 AsBaseUnit() - { - switch(Unit) - { - case VolumeUnit.AuTablespoon: return _value*2e-5; - case VolumeUnit.Centiliter: return (_value/1e3) * 1e-2d; - case VolumeUnit.CubicCentimeter: return _value/1e6; - case VolumeUnit.CubicDecimeter: return _value/1e3; - case VolumeUnit.CubicFoot: return _value*0.0283168; - case VolumeUnit.CubicInch: return _value*1.6387*1e-5; - case VolumeUnit.CubicKilometer: return _value*1e9; - case VolumeUnit.CubicMeter: return _value; - case VolumeUnit.CubicMicrometer: return _value/1e18; - case VolumeUnit.CubicMile: return _value*4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return _value/1e9; - case VolumeUnit.CubicYard: return _value*0.764554858; - case VolumeUnit.Deciliter: return (_value/1e3) * 1e-1d; - case VolumeUnit.HectocubicFoot: return (_value*0.0283168) * 1e2d; - case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; - case VolumeUnit.Hectoliter: return (_value/1e3) * 1e2d; - case VolumeUnit.ImperialBeerBarrel: return _value*0.16365924; - case VolumeUnit.ImperialGallon: return _value*0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return _value*2.8413062499962901241875439064617e-5; - case VolumeUnit.KilocubicFoot: return (_value*0.0283168) * 1e3d; - case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; - case VolumeUnit.KiloimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e3d; - case VolumeUnit.KilousGallon: return (_value*0.00378541) * 1e3d; - case VolumeUnit.Liter: return _value/1e3; - case VolumeUnit.MegacubicFoot: return (_value*0.0283168) * 1e6d; - case VolumeUnit.MegaimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e6d; - case VolumeUnit.MegausGallon: return (_value*0.00378541) * 1e6d; - case VolumeUnit.MetricCup: return _value*0.00025; - case VolumeUnit.MetricTeaspoon: return _value*0.5e-5; - case VolumeUnit.Microliter: return (_value/1e3) * 1e-6d; - case VolumeUnit.Milliliter: return (_value/1e3) * 1e-3d; - case VolumeUnit.OilBarrel: return _value*0.158987294928; - case VolumeUnit.UkTablespoon: return _value*1.5e-5; - case VolumeUnit.UsBeerBarrel: return _value*0.1173477658; - case VolumeUnit.UsCustomaryCup: return _value*0.0002365882365; - case VolumeUnit.UsGallon: return _value*0.00378541; - case VolumeUnit.UsLegalCup: return _value*0.00024; - case VolumeUnit.UsOunce: return _value*2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return _value*4.73176473e-4; - case VolumeUnit.UsQuart: return _value*9.46352946e-4; - case VolumeUnit.UsTablespoon: return _value*1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return _value*4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeUnit.AuTablespoon: return baseUnitValue/2e-5; - case VolumeUnit.Centiliter: return (baseUnitValue*1e3) / 1e-2d; - case VolumeUnit.CubicCentimeter: return baseUnitValue*1e6; - case VolumeUnit.CubicDecimeter: return baseUnitValue*1e3; - case VolumeUnit.CubicFoot: return baseUnitValue/0.0283168; - case VolumeUnit.CubicInch: return baseUnitValue/(1.6387*1e-5); - case VolumeUnit.CubicKilometer: return baseUnitValue/1e9; - case VolumeUnit.CubicMeter: return baseUnitValue; - case VolumeUnit.CubicMicrometer: return baseUnitValue*1e18; - case VolumeUnit.CubicMile: return baseUnitValue/4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return baseUnitValue*1e9; - case VolumeUnit.CubicYard: return baseUnitValue/0.764554858; - case VolumeUnit.Deciliter: return (baseUnitValue*1e3) / 1e-1d; - case VolumeUnit.HectocubicFoot: return (baseUnitValue/0.0283168) / 1e2d; - case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; - case VolumeUnit.Hectoliter: return (baseUnitValue*1e3) / 1e2d; - case VolumeUnit.ImperialBeerBarrel: return baseUnitValue/0.16365924; - case VolumeUnit.ImperialGallon: return baseUnitValue/0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return baseUnitValue/2.8413062499962901241875439064617e-5; - case VolumeUnit.KilocubicFoot: return (baseUnitValue/0.0283168) / 1e3d; - case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; - case VolumeUnit.KiloimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e3d; - case VolumeUnit.KilousGallon: return (baseUnitValue/0.00378541) / 1e3d; - case VolumeUnit.Liter: return baseUnitValue*1e3; - case VolumeUnit.MegacubicFoot: return (baseUnitValue/0.0283168) / 1e6d; - case VolumeUnit.MegaimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e6d; - case VolumeUnit.MegausGallon: return (baseUnitValue/0.00378541) / 1e6d; - case VolumeUnit.MetricCup: return baseUnitValue/0.00025; - case VolumeUnit.MetricTeaspoon: return baseUnitValue/0.5e-5; - case VolumeUnit.Microliter: return (baseUnitValue*1e3) / 1e-6d; - case VolumeUnit.Milliliter: return (baseUnitValue*1e3) / 1e-3d; - case VolumeUnit.OilBarrel: return baseUnitValue/0.158987294928; - case VolumeUnit.UkTablespoon: return baseUnitValue/1.5e-5; - case VolumeUnit.UsBeerBarrel: return baseUnitValue/0.1173477658; - case VolumeUnit.UsCustomaryCup: return baseUnitValue/0.0002365882365; - case VolumeUnit.UsGallon: return baseUnitValue/0.00378541; - case VolumeUnit.UsLegalCup: return baseUnitValue/0.00024; - case VolumeUnit.UsOunce: return baseUnitValue/2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return baseUnitValue/4.73176473e-4; - case VolumeUnit.UsQuart: return baseUnitValue/9.46352946e-4; - case VolumeUnit.UsTablespoon: return baseUnitValue/1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return baseUnitValue/4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 Volume Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Volume result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out VolumeUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static Volume ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Volume result) - { - result = default(Volume); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static VolumeUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == VolumeUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out VolumeUnit unit) - { - unit = VolumeUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == VolumeUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(VolumeUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Volume - /// - public static Volume MaxValue => new Volume(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Volume - /// - public static Volume MinValue => new Volume(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Volume.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Volume.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs b/Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs deleted file mode 100644 index 1965904664..0000000000 --- a/Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs +++ /dev/null @@ -1,1087 +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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class VolumeFlow : IQuantity -#else - public partial struct VolumeFlow : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeFlowUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static VolumeFlow() - { - BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - VolumeFlow(double numericValue, VolumeFlowUnit unit) - { - if(unit == VolumeFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.VolumeFlow; - - /// - /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. - /// - public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the VolumeFlow quantity. - /// - public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); - - /// - /// Get VolumeFlow in CentilitersPerMinute. - /// - public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); - - /// - /// Get VolumeFlow in CubicDecimetersPerMinute. - /// - public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); - - /// - /// Get VolumeFlow in CubicFeetPerHour. - /// - public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); - - /// - /// Get VolumeFlow in CubicFeetPerMinute. - /// - public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); - - /// - /// Get VolumeFlow in CubicFeetPerSecond. - /// - public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); - - /// - /// Get VolumeFlow in CubicMetersPerHour. - /// - public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); - - /// - /// Get VolumeFlow in CubicMetersPerMinute. - /// - public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); - - /// - /// Get VolumeFlow in CubicMetersPerSecond. - /// - public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); - - /// - /// Get VolumeFlow in CubicYardsPerHour. - /// - public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); - - /// - /// Get VolumeFlow in CubicYardsPerMinute. - /// - public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); - - /// - /// Get VolumeFlow in CubicYardsPerSecond. - /// - public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); - - /// - /// Get VolumeFlow in DecilitersPerMinute. - /// - public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); - - /// - /// Get VolumeFlow in KilolitersPerMinute. - /// - public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); - - /// - /// Get VolumeFlow in LitersPerHour. - /// - public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); - - /// - /// Get VolumeFlow in LitersPerMinute. - /// - public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); - - /// - /// Get VolumeFlow in LitersPerSecond. - /// - public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); - - /// - /// Get VolumeFlow in MicrolitersPerMinute. - /// - public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); - - /// - /// Get VolumeFlow in MillilitersPerMinute. - /// - public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); - - /// - /// Get VolumeFlow in MillionUsGallonsPerDay. - /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); - - /// - /// Get VolumeFlow in NanolitersPerMinute. - /// - public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); - - /// - /// Get VolumeFlow in OilBarrelsPerDay. - /// - public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); - - /// - /// Get VolumeFlow in OilBarrelsPerHour. - /// - public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); - - /// - /// Get VolumeFlow in OilBarrelsPerMinute. - /// - public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); - - /// - /// Get VolumeFlow in UsGallonsPerHour. - /// - public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); - - /// - /// Get VolumeFlow in UsGallonsPerMinute. - /// - public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); - - /// - /// Get VolumeFlow in UsGallonsPerSecond. - /// - public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. - /// - public static VolumeFlow Zero => new VolumeFlow(0, BaseUnit); - - /// - /// Get VolumeFlow from CentilitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCentilitersPerMinute(double centilitersperminute) -#else - public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) -#endif - { - double value = (double) centilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); - } - - /// - /// Get VolumeFlow from CubicDecimetersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) -#else - public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) -#endif - { - double value = (double) cubicdecimetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); - } - - /// - /// Get VolumeFlow from CubicFeetPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerHour(double cubicfeetperhour) -#else - public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) -#endif - { - double value = (double) cubicfeetperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); - } - - /// - /// Get VolumeFlow from CubicFeetPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerMinute(double cubicfeetperminute) -#else - public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) -#endif - { - double value = (double) cubicfeetperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); - } - - /// - /// Get VolumeFlow from CubicFeetPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerSecond(double cubicfeetpersecond) -#else - public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) -#endif - { - double value = (double) cubicfeetpersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); - } - - /// - /// Get VolumeFlow from CubicMetersPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerHour(double cubicmetersperhour) -#else - public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) -#endif - { - double value = (double) cubicmetersperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); - } - - /// - /// Get VolumeFlow from CubicMetersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerMinute(double cubicmetersperminute) -#else - public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) -#endif - { - double value = (double) cubicmetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); - } - - /// - /// Get VolumeFlow from CubicMetersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerSecond(double cubicmeterspersecond) -#else - public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) -#endif - { - double value = (double) cubicmeterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); - } - - /// - /// Get VolumeFlow from CubicYardsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerHour(double cubicyardsperhour) -#else - public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) -#endif - { - double value = (double) cubicyardsperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); - } - - /// - /// Get VolumeFlow from CubicYardsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerMinute(double cubicyardsperminute) -#else - public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) -#endif - { - double value = (double) cubicyardsperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); - } - - /// - /// Get VolumeFlow from CubicYardsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerSecond(double cubicyardspersecond) -#else - public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) -#endif - { - double value = (double) cubicyardspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); - } - - /// - /// Get VolumeFlow from DecilitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromDecilitersPerMinute(double decilitersperminute) -#else - public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) -#endif - { - double value = (double) decilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); - } - - /// - /// Get VolumeFlow from KilolitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilolitersPerMinute(double kilolitersperminute) -#else - public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) -#endif - { - double value = (double) kilolitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); - } - - /// - /// Get VolumeFlow from LitersPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerHour(double litersperhour) -#else - public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) -#endif - { - double value = (double) litersperhour; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); - } - - /// - /// Get VolumeFlow from LitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerMinute(double litersperminute) -#else - public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) -#endif - { - double value = (double) litersperminute; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); - } - - /// - /// Get VolumeFlow from LitersPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerSecond(double literspersecond) -#else - public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) -#endif - { - double value = (double) literspersecond; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); - } - - /// - /// Get VolumeFlow from MicrolitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMicrolitersPerMinute(double microlitersperminute) -#else - public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) -#endif - { - double value = (double) microlitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); - } - - /// - /// Get VolumeFlow from MillilitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillilitersPerMinute(double millilitersperminute) -#else - public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) -#endif - { - double value = (double) millilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); - } - - /// - /// Get VolumeFlow from MillionUsGallonsPerDay. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) -#else - public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) -#endif - { - double value = (double) millionusgallonsperday; - return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); - } - - /// - /// Get VolumeFlow from NanolitersPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromNanolitersPerMinute(double nanolitersperminute) -#else - public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) -#endif - { - double value = (double) nanolitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); - } - - /// - /// Get VolumeFlow from OilBarrelsPerDay. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerDay(double oilbarrelsperday) -#else - public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) -#endif - { - double value = (double) oilbarrelsperday; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); - } - - /// - /// Get VolumeFlow from OilBarrelsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerHour(double oilbarrelsperhour) -#else - public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) -#endif - { - double value = (double) oilbarrelsperhour; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); - } - - /// - /// Get VolumeFlow from OilBarrelsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerMinute(double oilbarrelsperminute) -#else - public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminute) -#endif - { - double value = (double) oilbarrelsperminute; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); - } - - /// - /// Get VolumeFlow from UsGallonsPerHour. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerHour(double usgallonsperhour) -#else - public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) -#endif - { - double value = (double) usgallonsperhour; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); - } - - /// - /// Get VolumeFlow from UsGallonsPerMinute. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerMinute(double usgallonsperminute) -#else - public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) -#endif - { - double value = (double) usgallonsperminute; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); - } - - /// - /// Get VolumeFlow from UsGallonsPerSecond. - /// - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerSecond(double usgallonspersecond) -#else - public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) -#endif - { - double value = (double) usgallonspersecond; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumeFlow unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) -#else - public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) -#endif - { - return new VolumeFlow((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VolumeFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is VolumeFlow)) throw new ArgumentException("Expected type VolumeFlow.", nameof(obj)); - - return CompareTo((VolumeFlow)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(VolumeFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VolumeFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeFlow. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumeFlow to another VolumeFlow with the unit representation . - /// - /// A VolumeFlow with the specified unit. - public VolumeFlow ToUnit(VolumeFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumeFlow(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 AsBaseUnit() - { - switch(Unit) - { - case VolumeFlowUnit.CentiliterPerMinute: return (_value/60000.00000) * 1e-2d; - case VolumeFlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return _value/2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return _value/35.314666721; - case VolumeFlowUnit.CubicMeterPerHour: return _value/3600; - case VolumeFlowUnit.CubicMeterPerMinute: return _value/60; - case VolumeFlowUnit.CubicMeterPerSecond: return _value; - case VolumeFlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return _value*0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return _value*0.764554857984; - case VolumeFlowUnit.DeciliterPerMinute: return (_value/60000.00000) * 1e-1d; - case VolumeFlowUnit.KiloliterPerMinute: return (_value/60000.00000) * 1e3d; - case VolumeFlowUnit.LiterPerHour: return _value/3600000.000; - case VolumeFlowUnit.LiterPerMinute: return _value/60000.00000; - case VolumeFlowUnit.LiterPerSecond: return _value/1000; - case VolumeFlowUnit.MicroliterPerMinute: return (_value/60000.00000) * 1e-6d; - case VolumeFlowUnit.MilliliterPerMinute: return (_value/60000.00000) * 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; - case VolumeFlowUnit.NanoliterPerMinute: return (_value/60000.00000) * 1e-9d; - case VolumeFlowUnit.OilBarrelPerDay: return _value*1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelPerHour: return _value*4.41631375e-5; - case VolumeFlowUnit.OilBarrelPerMinute: return _value*2.64978825e-3; - case VolumeFlowUnit.UsGallonPerHour: return _value/951019.38848933424; - case VolumeFlowUnit.UsGallonPerMinute: return _value/15850.323141489; - case VolumeFlowUnit.UsGallonPerSecond: return _value/264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeFlowUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeFlowUnit.CentiliterPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; - case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; - case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue*3600; - case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue*60; - case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; - case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; - case VolumeFlowUnit.DeciliterPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; - case VolumeFlowUnit.KiloliterPerMinute: return (baseUnitValue*60000.00000) / 1e3d; - case VolumeFlowUnit.LiterPerHour: return baseUnitValue*3600000.000; - case VolumeFlowUnit.LiterPerMinute: return baseUnitValue*60000.00000; - case VolumeFlowUnit.LiterPerSecond: return baseUnitValue*1000; - case VolumeFlowUnit.MicroliterPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; - case VolumeFlowUnit.MilliliterPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; - case VolumeFlowUnit.NanoliterPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; - case VolumeFlowUnit.OilBarrelPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelPerHour: return baseUnitValue/4.41631375e-5; - case VolumeFlowUnit.OilBarrelPerMinute: return baseUnitValue/2.64978825e-3; - case VolumeFlowUnit.UsGallonPerHour: return baseUnitValue*951019.38848933424; - case VolumeFlowUnit.UsGallonPerMinute: return baseUnitValue*15850.323141489; - case VolumeFlowUnit.UsGallonPerSecond: return baseUnitValue*264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 VolumeFlow Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumeFlow result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeFlowUnit ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out VolumeFlowUnit unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static VolumeFlow ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out VolumeFlow result) - { - result = default(VolumeFlow); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static VolumeFlowUnit ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse(str, provider); - - if (unit == VolumeFlowUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeFlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out VolumeFlowUnit unit) - { - unit = VolumeFlowUnit.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse(str, provider, out unit)) - return false; - - if(unit == VolumeFlowUnit.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(VolumeFlowUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of VolumeFlow - /// - public static VolumeFlow MaxValue => new VolumeFlow(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of VolumeFlow - /// - public static VolumeFlow MinValue => new VolumeFlow(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => VolumeFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs index e79efac2f0..d7d30a6586 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs @@ -37,8 +37,10 @@ using System; using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -47,18 +49,25 @@ namespace UnitsNet /// /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Information + public sealed partial class Information : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly InformationUnit? _unit; + static Information() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Bit. /// @@ -71,28 +80,529 @@ public Information() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Information(decimal numericValue, InformationUnit unit) + { + if(unit == InformationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Information, which is Bit. All conversions go via this value. + /// + public static InformationUnit BaseUnit => InformationUnit.Bit; + + /// + /// Represents the largest possible value of Information + /// + public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Information + /// + public static Information MinValue => new Information(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Information; + + /// + /// All units of measurement for the Information quantity. + /// + public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Bit. + /// + public static Information Zero => new Information(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Information.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Information.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Information in Bits. + /// + public double Bits => As(InformationUnit.Bit); + + /// + /// Get Information in Bytes. + /// + public double Bytes => As(InformationUnit.Byte); + + /// + /// Get Information in Exabits. + /// + public double Exabits => As(InformationUnit.Exabit); + + /// + /// Get Information in Exabytes. + /// + public double Exabytes => As(InformationUnit.Exabyte); + + /// + /// Get Information in Exbibits. + /// + public double Exbibits => As(InformationUnit.Exbibit); + + /// + /// Get Information in Exbibytes. + /// + public double Exbibytes => As(InformationUnit.Exbibyte); + + /// + /// Get Information in Gibibits. + /// + public double Gibibits => As(InformationUnit.Gibibit); + + /// + /// Get Information in Gibibytes. + /// + public double Gibibytes => As(InformationUnit.Gibibyte); + + /// + /// Get Information in Gigabits. + /// + public double Gigabits => As(InformationUnit.Gigabit); + + /// + /// Get Information in Gigabytes. + /// + public double Gigabytes => As(InformationUnit.Gigabyte); + + /// + /// Get Information in Kibibits. + /// + public double Kibibits => As(InformationUnit.Kibibit); + + /// + /// Get Information in Kibibytes. + /// + public double Kibibytes => As(InformationUnit.Kibibyte); + + /// + /// Get Information in Kilobits. + /// + public double Kilobits => As(InformationUnit.Kilobit); + + /// + /// Get Information in Kilobytes. + /// + public double Kilobytes => As(InformationUnit.Kilobyte); + + /// + /// Get Information in Mebibits. + /// + public double Mebibits => As(InformationUnit.Mebibit); + + /// + /// Get Information in Mebibytes. + /// + public double Mebibytes => As(InformationUnit.Mebibyte); + + /// + /// Get Information in Megabits. + /// + public double Megabits => As(InformationUnit.Megabit); + + /// + /// Get Information in Megabytes. + /// + public double Megabytes => As(InformationUnit.Megabyte); + + /// + /// Get Information in Pebibits. + /// + public double Pebibits => As(InformationUnit.Pebibit); + + /// + /// Get Information in Pebibytes. + /// + public double Pebibytes => As(InformationUnit.Pebibyte); + + /// + /// Get Information in Petabits. + /// + public double Petabits => As(InformationUnit.Petabit); + + /// + /// Get Information in Petabytes. + /// + public double Petabytes => As(InformationUnit.Petabyte); + + /// + /// Get Information in Tebibits. + /// + public double Tebibits => As(InformationUnit.Tebibit); + + /// + /// Get Information in Tebibytes. + /// + public double Tebibytes => As(InformationUnit.Tebibyte); + + /// + /// Get Information in Terabits. + /// + public double Terabits => As(InformationUnit.Terabit); + + /// + /// Get Information in Terabytes. + /// + public double Terabytes => As(InformationUnit.Terabyte); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(InformationUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to if null. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(InformationUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - #region Parsing + #endregion + + #region Static Factory Methods + + /// + /// Get Information from Bits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromBits(double bits) + { + decimal value = (decimal) bits; + return new Information(value, InformationUnit.Bit); + } + /// + /// Get Information from Bytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromBytes(double bytes) + { + decimal value = (decimal) bytes; + return new Information(value, InformationUnit.Byte); + } + /// + /// Get Information from Exabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExabits(double exabits) + { + decimal value = (decimal) exabits; + return new Information(value, InformationUnit.Exabit); + } + /// + /// Get Information from Exabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExabytes(double exabytes) + { + decimal value = (decimal) exabytes; + return new Information(value, InformationUnit.Exabyte); + } + /// + /// Get Information from Exbibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExbibits(double exbibits) + { + decimal value = (decimal) exbibits; + return new Information(value, InformationUnit.Exbibit); + } + /// + /// Get Information from Exbibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExbibytes(double exbibytes) + { + decimal value = (decimal) exbibytes; + return new Information(value, InformationUnit.Exbibyte); + } + /// + /// Get Information from Gibibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGibibits(double gibibits) + { + decimal value = (decimal) gibibits; + return new Information(value, InformationUnit.Gibibit); + } + /// + /// Get Information from Gibibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGibibytes(double gibibytes) + { + decimal value = (decimal) gibibytes; + return new Information(value, InformationUnit.Gibibyte); + } + /// + /// Get Information from Gigabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGigabits(double gigabits) + { + decimal value = (decimal) gigabits; + return new Information(value, InformationUnit.Gigabit); + } + /// + /// Get Information from Gigabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGigabytes(double gigabytes) + { + decimal value = (decimal) gigabytes; + return new Information(value, InformationUnit.Gigabyte); + } + /// + /// Get Information from Kibibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKibibits(double kibibits) + { + decimal value = (decimal) kibibits; + return new Information(value, InformationUnit.Kibibit); + } + /// + /// Get Information from Kibibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKibibytes(double kibibytes) + { + decimal value = (decimal) kibibytes; + return new Information(value, InformationUnit.Kibibyte); + } + /// + /// Get Information from Kilobits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKilobits(double kilobits) + { + decimal value = (decimal) kilobits; + return new Information(value, InformationUnit.Kilobit); + } + /// + /// Get Information from Kilobytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKilobytes(double kilobytes) + { + decimal value = (decimal) kilobytes; + return new Information(value, InformationUnit.Kilobyte); + } + /// + /// Get Information from Mebibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMebibits(double mebibits) + { + decimal value = (decimal) mebibits; + return new Information(value, InformationUnit.Mebibit); + } + /// + /// Get Information from Mebibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMebibytes(double mebibytes) + { + decimal value = (decimal) mebibytes; + return new Information(value, InformationUnit.Mebibyte); + } + /// + /// Get Information from Megabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMegabits(double megabits) + { + decimal value = (decimal) megabits; + return new Information(value, InformationUnit.Megabit); + } + /// + /// Get Information from Megabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMegabytes(double megabytes) + { + decimal value = (decimal) megabytes; + return new Information(value, InformationUnit.Megabyte); + } + /// + /// Get Information from Pebibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPebibits(double pebibits) + { + decimal value = (decimal) pebibits; + return new Information(value, InformationUnit.Pebibit); + } + /// + /// Get Information from Pebibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPebibytes(double pebibytes) + { + decimal value = (decimal) pebibytes; + return new Information(value, InformationUnit.Pebibyte); + } + /// + /// Get Information from Petabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPetabits(double petabits) + { + decimal value = (decimal) petabits; + return new Information(value, InformationUnit.Petabit); + } + /// + /// Get Information from Petabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPetabytes(double petabytes) + { + decimal value = (decimal) petabytes; + return new Information(value, InformationUnit.Petabyte); + } + /// + /// Get Information from Tebibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTebibits(double tebibits) + { + decimal value = (decimal) tebibits; + return new Information(value, InformationUnit.Tebibit); + } + /// + /// Get Information from Tebibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTebibytes(double tebibytes) + { + decimal value = (decimal) tebibytes; + return new Information(value, InformationUnit.Tebibyte); + } + /// + /// Get Information from Terabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTerabits(double terabits) + { + decimal value = (decimal) terabits; + return new Information(value, InformationUnit.Terabit); + } + /// + /// Get Information from Terabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTerabytes(double terabytes) + { + decimal value = (decimal) terabytes; + return new Information(value, InformationUnit.Terabyte); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Information unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Information From(double value, InformationUnit fromUnit) + { + return new Information((decimal)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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -111,13 +621,37 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Information Parse(string str, [CanBeNull] string cultureName) + public static Information Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return ParseInternal(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", new CultureInfo("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. + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static Information Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return ParseInternal(str, provider); } @@ -125,16 +659,28 @@ public static Information Parse(string str, [CanBeNull] string cultureName) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Information result) + public static bool TryParse([CanBeNull] string str, out Information result) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return TryParseInternal(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", new CultureInfo("en-US")); + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Information result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return TryParseInternal(str, provider, out result); } @@ -142,84 +688,410 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureNa /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static InformationUnit ParseUnit(string str) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return ParseUnitInternal(str, null); + } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return ParseUnitInternal(str, provider); } + public static bool TryParseUnit(string str, out InformationUnit unit) + { + return TryParseUnitInternal(str, null, out unit); + } + /// - /// Try to parse a unit string. + /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// The parsed unit if successful. /// True if successful, otherwise false. /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out InformationUnit unit) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return TryParseUnitInternal(str, provider, out unit); } + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.Parse("5.5 m", new CultureInfo("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. + /// + private static Information ParseInternal(string str, [CanBeNull] IFormatProvider provider) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} + /// Format to use when parsing number and unit. Defaults to . + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) + { + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + private static InformationUnit ParseUnitInternal(string str, IFormatProvider provider = null) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse(str.Trim(), provider); + + if (unit == InformationUnit.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized InformationUnit."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out InformationUnit unit) + { + unit = InformationUnit.Undefined; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + if(!UnitParser.Default.TryParse(str.Trim(), provider, out unit)) + return false; + + if(unit == InformationUnit.Undefined) + return false; + + return true; + } + + #endregion + + #region Equality / IComparable + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is Information)) throw new ArgumentException("Expected type Information.", nameof(obj)); + + return CompareTo((Information)obj); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + internal int CompareTo(Information other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another Information within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Information other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Information. + public override int GetHashCode() + { + return new { Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(InformationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Information to another Information with the unit representation . + /// + /// A Information with the specified unit. + public Information ToUnit(InformationUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Information(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 decimal AsBaseUnit() + { + switch(Unit) + { + case InformationUnit.Bit: return _value; + case InformationUnit.Byte: return _value*8m; + case InformationUnit.Exabit: return (_value) * 1e18m; + case InformationUnit.Exabyte: return (_value*8m) * 1e18m; + case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Exbibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); + case InformationUnit.Gibibyte: return (_value*8m) * (1024m * 1024 * 1024); + case InformationUnit.Gigabit: return (_value) * 1e9m; + case InformationUnit.Gigabyte: return (_value*8m) * 1e9m; + case InformationUnit.Kibibit: return (_value) * 1024m; + case InformationUnit.Kibibyte: return (_value*8m) * 1024m; + case InformationUnit.Kilobit: return (_value) * 1e3m; + case InformationUnit.Kilobyte: return (_value*8m) * 1e3m; + case InformationUnit.Mebibit: return (_value) * (1024m * 1024); + case InformationUnit.Mebibyte: return (_value*8m) * (1024m * 1024); + case InformationUnit.Megabit: return (_value) * 1e6m; + case InformationUnit.Megabyte: return (_value*8m) * 1e6m; + case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Pebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Petabit: return (_value) * 1e15m; + case InformationUnit.Petabyte: return (_value*8m) * 1e15m; + case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); + case InformationUnit.Tebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024); + case InformationUnit.Terabit: return (_value) * 1e12m; + case InformationUnit.Terabyte: return (_value*8m) * 1e12m; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private decimal AsBaseNumericType(InformationUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case InformationUnit.Bit: return baseUnitValue; + case InformationUnit.Byte: return baseUnitValue/8m; + case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; + case InformationUnit.Exabyte: return (baseUnitValue/8m) / 1e18m; + case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Exbibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); + case InformationUnit.Gibibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024); + case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; + case InformationUnit.Gigabyte: return (baseUnitValue/8m) / 1e9m; + case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; + case InformationUnit.Kibibyte: return (baseUnitValue/8m) / 1024m; + case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; + case InformationUnit.Kilobyte: return (baseUnitValue/8m) / 1e3m; + case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); + case InformationUnit.Mebibyte: return (baseUnitValue/8m) / (1024m * 1024); + case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; + case InformationUnit.Megabyte: return (baseUnitValue/8m) / 1e6m; + case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Pebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; + case InformationUnit.Petabyte: return (baseUnitValue/8m) / 1e15m; + case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); + case InformationUnit.Tebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); + case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; + case InformationUnit.Terabyte: return (baseUnitValue/8m) / 1e12m; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(Unit); + } + + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString(InformationUnit unit) + { + return ToString(unit, null, 2); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(InformationUnit unit, [CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(unit, provider, 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(InformationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) { + var provider = cultureName; double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + return ToString(unit, provider, format); } /// /// Get string representation of value and unit. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(InformationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; double value = As(unit); object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); @@ -227,5 +1099,10 @@ public string ToString(InformationUnit unit, [CanBeNull] string cultureName, [No } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs index c4cfae8972..6b72f87fee 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs @@ -37,8 +37,10 @@ using System; using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -47,18 +49,25 @@ namespace UnitsNet /// /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Length + public sealed partial class Length : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LengthUnit? _unit; + + static Length() + { + BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Meter. /// @@ -71,28 +80,469 @@ public Length() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Length(double numericValue, LengthUnit unit) + { + if(unit == LengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Length, which is Meter. All conversions go via this value. + /// + public static LengthUnit BaseUnit => LengthUnit.Meter; + + /// + /// Represents the largest possible value of Length + /// + public static Length MaxValue => new Length(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Length + /// + public static Length MinValue => new Length(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Length; + + /// + /// All units of measurement for the Length quantity. + /// + public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Meter. + /// + public static Length Zero => new Length(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Length.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Length.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Length in Centimeters. + /// + public double Centimeters => As(LengthUnit.Centimeter); + + /// + /// Get Length in Decimeters. + /// + public double Decimeters => As(LengthUnit.Decimeter); + + /// + /// Get Length in DtpPicas. + /// + public double DtpPicas => As(LengthUnit.DtpPica); + + /// + /// Get Length in DtpPoints. + /// + public double DtpPoints => As(LengthUnit.DtpPoint); + + /// + /// Get Length in Fathoms. + /// + public double Fathoms => As(LengthUnit.Fathom); + + /// + /// Get Length in Feet. + /// + public double Feet => As(LengthUnit.Foot); + + /// + /// Get Length in Inches. + /// + public double Inches => As(LengthUnit.Inch); + + /// + /// Get Length in Kilometers. + /// + public double Kilometers => As(LengthUnit.Kilometer); + + /// + /// Get Length in Meters. + /// + public double Meters => As(LengthUnit.Meter); + + /// + /// Get Length in Microinches. + /// + public double Microinches => As(LengthUnit.Microinch); + + /// + /// Get Length in Micrometers. + /// + public double Micrometers => As(LengthUnit.Micrometer); + + /// + /// Get Length in Mils. + /// + public double Mils => As(LengthUnit.Mil); + + /// + /// Get Length in Miles. + /// + public double Miles => As(LengthUnit.Mile); + + /// + /// Get Length in Millimeters. + /// + public double Millimeters => As(LengthUnit.Millimeter); + + /// + /// Get Length in Nanometers. + /// + public double Nanometers => As(LengthUnit.Nanometer); + + /// + /// Get Length in NauticalMiles. + /// + public double NauticalMiles => As(LengthUnit.NauticalMile); + + /// + /// Get Length in PrinterPicas. + /// + public double PrinterPicas => As(LengthUnit.PrinterPica); + + /// + /// Get Length in PrinterPoints. + /// + public double PrinterPoints => As(LengthUnit.PrinterPoint); + + /// + /// Get Length in Shackles. + /// + public double Shackles => As(LengthUnit.Shackle); + + /// + /// Get Length in Twips. + /// + public double Twips => As(LengthUnit.Twip); + + /// + /// Get Length in UsSurveyFeet. + /// + public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + + /// + /// Get Length in Yards. + /// + public double Yards => As(LengthUnit.Yard); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LengthUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to if null. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LengthUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - #region Parsing + #endregion + + #region Static Factory Methods + + /// + /// Get Length from Centimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromCentimeters(double centimeters) + { + double value = (double) centimeters; + return new Length(value, LengthUnit.Centimeter); + } + /// + /// Get Length from Decimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromDecimeters(double decimeters) + { + double value = (double) decimeters; + return new Length(value, LengthUnit.Decimeter); + } + /// + /// Get Length from DtpPicas. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromDtpPicas(double dtppicas) + { + double value = (double) dtppicas; + return new Length(value, LengthUnit.DtpPica); + } + /// + /// Get Length from DtpPoints. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromDtpPoints(double dtppoints) + { + double value = (double) dtppoints; + return new Length(value, LengthUnit.DtpPoint); + } + /// + /// Get Length from Fathoms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromFathoms(double fathoms) + { + double value = (double) fathoms; + return new Length(value, LengthUnit.Fathom); + } + /// + /// Get Length from Feet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromFeet(double feet) + { + double value = (double) feet; + return new Length(value, LengthUnit.Foot); + } + /// + /// Get Length from Inches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromInches(double inches) + { + double value = (double) inches; + return new Length(value, LengthUnit.Inch); + } + /// + /// Get Length from Kilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromKilometers(double kilometers) + { + double value = (double) kilometers; + return new Length(value, LengthUnit.Kilometer); + } + /// + /// Get Length from Meters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMeters(double meters) + { + double value = (double) meters; + return new Length(value, LengthUnit.Meter); + } + /// + /// Get Length from Microinches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMicroinches(double microinches) + { + double value = (double) microinches; + return new Length(value, LengthUnit.Microinch); + } + /// + /// Get Length from Micrometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMicrometers(double micrometers) + { + double value = (double) micrometers; + return new Length(value, LengthUnit.Micrometer); + } + /// + /// Get Length from Mils. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMils(double mils) + { + double value = (double) mils; + return new Length(value, LengthUnit.Mil); + } + /// + /// Get Length from Miles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMiles(double miles) + { + double value = (double) miles; + return new Length(value, LengthUnit.Mile); + } + /// + /// Get Length from Millimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMillimeters(double millimeters) + { + double value = (double) millimeters; + return new Length(value, LengthUnit.Millimeter); + } + /// + /// Get Length from Nanometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromNanometers(double nanometers) + { + double value = (double) nanometers; + return new Length(value, LengthUnit.Nanometer); + } + /// + /// Get Length from NauticalMiles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromNauticalMiles(double nauticalmiles) + { + double value = (double) nauticalmiles; + return new Length(value, LengthUnit.NauticalMile); + } + /// + /// Get Length from PrinterPicas. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromPrinterPicas(double printerpicas) + { + double value = (double) printerpicas; + return new Length(value, LengthUnit.PrinterPica); + } + /// + /// Get Length from PrinterPoints. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromPrinterPoints(double printerpoints) + { + double value = (double) printerpoints; + return new Length(value, LengthUnit.PrinterPoint); + } + /// + /// Get Length from Shackles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromShackles(double shackles) + { + double value = (double) shackles; + return new Length(value, LengthUnit.Shackle); + } + /// + /// Get Length from Twips. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromTwips(double twips) + { + double value = (double) twips; + return new Length(value, LengthUnit.Twip); + } + /// + /// Get Length from UsSurveyFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromUsSurveyFeet(double ussurveyfeet) + { + double value = (double) ussurveyfeet; + return new Length(value, LengthUnit.UsSurveyFoot); + } + /// + /// Get Length from Yards. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromYards(double yards) + { + double value = (double) yards; + return new Length(value, LengthUnit.Yard); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Length unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Length From(double value, LengthUnit fromUnit) + { + return new Length((double)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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -111,13 +561,37 @@ public static string GetAbbreviation(LengthUnit unit, [CanBeNull] string culture /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Length Parse(string str, [CanBeNull] string cultureName) + public static Length Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return ParseInternal(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", new CultureInfo("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. + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static Length Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return ParseInternal(str, provider); } @@ -125,16 +599,28 @@ public static Length Parse(string str, [CanBeNull] string cultureName) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Length result) + public static bool TryParse([CanBeNull] string str, out Length result) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return TryParseInternal(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", new CultureInfo("en-US")); + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Length result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return TryParseInternal(str, provider, out result); } @@ -142,84 +628,402 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureNa /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LengthUnit ParseUnit(string str) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return ParseUnitInternal(str, null); + } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return ParseUnitInternal(str, provider); } + public static bool TryParseUnit(string str, out LengthUnit unit) + { + return TryParseUnitInternal(str, null, out unit); + } + /// - /// Try to parse a unit string. + /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// The parsed unit if successful. /// True if successful, otherwise false. /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LengthUnit unit) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return TryParseUnitInternal(str, provider, out unit); } + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.Parse("5.5 m", new CultureInfo("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. + /// + private static Length ParseInternal(string str, [CanBeNull] IFormatProvider provider) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} + /// Format to use when parsing number and unit. Defaults to . + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Length result) + { + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + private static LengthUnit ParseUnitInternal(string str, IFormatProvider provider = null) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse(str.Trim(), provider); + + if (unit == LengthUnit.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LengthUnit."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LengthUnit unit) + { + unit = LengthUnit.Undefined; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + if(!UnitParser.Default.TryParse(str.Trim(), provider, out unit)) + return false; + + if(unit == LengthUnit.Undefined) + return false; + + return true; + } + + #endregion + + #region Equality / IComparable + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is Length)) throw new ArgumentException("Expected type Length.", nameof(obj)); + + return CompareTo((Length)obj); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + internal int CompareTo(Length other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another Length within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Length other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Length. + public override int GetHashCode() + { + return new { Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Length to another Length with the unit representation . + /// + /// A Length with the specified unit. + public Length ToUnit(LengthUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Length(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 AsBaseUnit() + { + switch(Unit) + { + case LengthUnit.Centimeter: return (_value) * 1e-2d; + case LengthUnit.Decimeter: return (_value) * 1e-1d; + case LengthUnit.DtpPica: return _value/236.220472441; + case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; + case LengthUnit.Fathom: return _value*1.8288; + case LengthUnit.Foot: return _value*0.3048; + case LengthUnit.Inch: return _value*2.54e-2; + case LengthUnit.Kilometer: return (_value) * 1e3d; + case LengthUnit.Meter: return _value; + case LengthUnit.Microinch: return _value*2.54e-8; + case LengthUnit.Micrometer: return (_value) * 1e-6d; + case LengthUnit.Mil: return _value*2.54e-5; + case LengthUnit.Mile: return _value*1609.34; + case LengthUnit.Millimeter: return (_value) * 1e-3d; + case LengthUnit.Nanometer: return (_value) * 1e-9d; + case LengthUnit.NauticalMile: return _value*1852; + case LengthUnit.PrinterPica: return _value/237.106301584; + case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; + case LengthUnit.Shackle: return _value*27.432; + case LengthUnit.Twip: return _value/56692.913385826; + case LengthUnit.UsSurveyFoot: return _value*1200/3937; + case LengthUnit.Yard: return _value*0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(LengthUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; + case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; + case LengthUnit.DtpPica: return baseUnitValue*236.220472441; + case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; + case LengthUnit.Fathom: return baseUnitValue/1.8288; + case LengthUnit.Foot: return baseUnitValue/0.3048; + case LengthUnit.Inch: return baseUnitValue/2.54e-2; + case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; + case LengthUnit.Meter: return baseUnitValue; + case LengthUnit.Microinch: return baseUnitValue/2.54e-8; + case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; + case LengthUnit.Mil: return baseUnitValue/2.54e-5; + case LengthUnit.Mile: return baseUnitValue/1609.34; + case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; + case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; + case LengthUnit.NauticalMile: return baseUnitValue/1852; + case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; + case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; + case LengthUnit.Shackle: return baseUnitValue/27.432; + case LengthUnit.Twip: return baseUnitValue*56692.913385826; + case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; + case LengthUnit.Yard: return baseUnitValue/0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(Unit); + } + + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString(LengthUnit unit) + { + return ToString(unit, null, 2); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(LengthUnit unit, [CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(unit, provider, 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(LengthUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) { + var provider = cultureName; double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + return ToString(unit, provider, format); } /// /// Get string representation of value and unit. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(LengthUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; double value = As(unit); object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); @@ -227,5 +1031,10 @@ public string ToString(LengthUnit unit, [CanBeNull] string cultureName, [NotNull } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs index 5f81235665..5149db52ad 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs @@ -37,8 +37,10 @@ using System; using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -47,18 +49,25 @@ namespace UnitsNet /// /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Level + public sealed partial class Level : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LevelUnit? _unit; + static Level() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Decibel. /// @@ -71,28 +80,169 @@ public Level() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Level(double numericValue, LevelUnit unit) + { + if(unit == LevelUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Level, which is Decibel. All conversions go via this value. + /// + public static LevelUnit BaseUnit => LevelUnit.Decibel; + + /// + /// Represents the largest possible value of Level + /// + public static Level MaxValue => new Level(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Level + /// + public static Level MinValue => new Level(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Level; + + /// + /// All units of measurement for the Level quantity. + /// + public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. + /// + public static Level Zero => new Level(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Level.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Level.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Level in Decibels. + /// + public double Decibels => As(LevelUnit.Decibel); + + /// + /// Get Level in Nepers. + /// + public double Nepers => As(LevelUnit.Neper); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LevelUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to if null. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LevelUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - #region Parsing + #endregion + + #region Static Factory Methods + + /// + /// Get Level from Decibels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Level FromDecibels(double decibels) + { + double value = (double) decibels; + return new Level(value, LevelUnit.Decibel); + } + /// + /// Get Level from Nepers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Level FromNepers(double nepers) + { + double value = (double) nepers; + return new Level(value, LevelUnit.Neper); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Level unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Level From(double value, LevelUnit fromUnit) + { + return new Level((double)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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -111,13 +261,37 @@ public static string GetAbbreviation(LevelUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Level Parse(string str, [CanBeNull] string cultureName) + public static Level Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return ParseInternal(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", new CultureInfo("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. + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static Level Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return ParseInternal(str, provider); } @@ -125,16 +299,28 @@ public static Level Parse(string str, [CanBeNull] string cultureName) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Level result) + public static bool TryParse([CanBeNull] string str, out Level result) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return TryParseInternal(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", new CultureInfo("en-US")); + /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Level result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return TryParseInternal(str, provider, out result); } @@ -142,84 +328,362 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureNa /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LevelUnit ParseUnit(string str) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + return ParseUnitInternal(str, null); + } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return ParseUnitInternal(str, provider); } + public static bool TryParseUnit(string str, out LevelUnit unit) + { + return TryParseUnitInternal(str, null, out unit); + } + /// - /// Try to parse a unit string. + /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. /// The parsed unit if successful. /// True if successful, otherwise false. /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LevelUnit unit) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return TryParseUnitInternal(str, provider, out unit); } + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.Parse("5.5 m", new CultureInfo("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. + /// + private static Level ParseInternal(string str, [CanBeNull] IFormatProvider provider) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} + /// Format to use when parsing number and unit. Defaults to . + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) + { + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + private static LevelUnit ParseUnitInternal(string str, IFormatProvider provider = null) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse(str.Trim(), provider); + + if (unit == LevelUnit.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LevelUnit."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LevelUnit unit) + { + unit = LevelUnit.Undefined; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + if(!UnitParser.Default.TryParse(str.Trim(), provider, out unit)) + return false; + + if(unit == LevelUnit.Undefined) + return false; + + return true; + } + + #endregion + + #region Equality / IComparable + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is Level)) throw new ArgumentException("Expected type Level.", nameof(obj)); + + return CompareTo((Level)obj); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + internal int CompareTo(Level other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another Level within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Level other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Level. + public override int GetHashCode() + { + return new { Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LevelUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Level to another Level with the unit representation . + /// + /// A Level with the specified unit. + public Level ToUnit(LevelUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Level(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 AsBaseUnit() + { + switch(Unit) + { + case LevelUnit.Decibel: return _value; + case LevelUnit.Neper: return (1/0.115129254)*_value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(LevelUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case LevelUnit.Decibel: return baseUnitValue; + case LevelUnit.Neper: return 0.115129254*baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(Unit); + } + + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString(LevelUnit unit) + { + return ToString(unit, null, 2); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(LevelUnit unit, [CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(unit, provider, 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(LevelUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) { + var provider = cultureName; double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + return ToString(unit, provider, format); } /// /// Get string representation of value and unit. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. public string ToString(LevelUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; double value = As(unit); object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); @@ -227,5 +691,10 @@ public string ToString(LevelUnit unit, [CanBeNull] string cultureName, [NotNull] } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj index 0162ca3fff..f54db87c4c 100644 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj +++ b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj @@ -98,7 +98,95 @@ PackageReference - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs index 1e89b9b6ea..d4f20f0030 100644 --- a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs @@ -20,6 +20,10 @@ // THE SOFTWARE. // ReSharper disable once CheckNamespace + +using System; +using UnitsNet.Units; + namespace UnitsNet { // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components diff --git a/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs index bce1c207a8..c304c11ff8 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs @@ -36,8 +36,11 @@ // THE SOFTWARE. using System; +using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -46,27 +49,754 @@ namespace UnitsNet /// /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// - // ReSharper disable once PartialTypeWithSinglePart + public partial struct Information : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly InformationUnit? _unit; + + static Information() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Information(decimal numericValue, InformationUnit unit) + { + if(unit == InformationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Information, which is Bit. All conversions go via this value. + /// + public static InformationUnit BaseUnit => InformationUnit.Bit; + + /// + /// Represents the largest possible value of Information + /// + public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Information + /// + public static Information MinValue => new Information(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Information; + + /// + /// All units of measurement for the Information quantity. + /// + public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Bit. + /// + public static Information Zero => new Information(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public decimal Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Information.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Information.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Information in Bits. + /// + public double Bits => As(InformationUnit.Bit); + + /// + /// Get Information in Bytes. + /// + public double Bytes => As(InformationUnit.Byte); + + /// + /// Get Information in Exabits. + /// + public double Exabits => As(InformationUnit.Exabit); + + /// + /// Get Information in Exabytes. + /// + public double Exabytes => As(InformationUnit.Exabyte); + + /// + /// Get Information in Exbibits. + /// + public double Exbibits => As(InformationUnit.Exbibit); + + /// + /// Get Information in Exbibytes. + /// + public double Exbibytes => As(InformationUnit.Exbibyte); + + /// + /// Get Information in Gibibits. + /// + public double Gibibits => As(InformationUnit.Gibibit); + + /// + /// Get Information in Gibibytes. + /// + public double Gibibytes => As(InformationUnit.Gibibyte); + + /// + /// Get Information in Gigabits. + /// + public double Gigabits => As(InformationUnit.Gigabit); + + /// + /// Get Information in Gigabytes. + /// + public double Gigabytes => As(InformationUnit.Gigabyte); + + /// + /// Get Information in Kibibits. + /// + public double Kibibits => As(InformationUnit.Kibibit); + + /// + /// Get Information in Kibibytes. + /// + public double Kibibytes => As(InformationUnit.Kibibyte); + + /// + /// Get Information in Kilobits. + /// + public double Kilobits => As(InformationUnit.Kilobit); + + /// + /// Get Information in Kilobytes. + /// + public double Kilobytes => As(InformationUnit.Kilobyte); + + /// + /// Get Information in Mebibits. + /// + public double Mebibits => As(InformationUnit.Mebibit); + + /// + /// Get Information in Mebibytes. + /// + public double Mebibytes => As(InformationUnit.Mebibyte); + + /// + /// Get Information in Megabits. + /// + public double Megabits => As(InformationUnit.Megabit); + + /// + /// Get Information in Megabytes. + /// + public double Megabytes => As(InformationUnit.Megabyte); + + /// + /// Get Information in Pebibits. + /// + public double Pebibits => As(InformationUnit.Pebibit); + + /// + /// Get Information in Pebibytes. + /// + public double Pebibytes => As(InformationUnit.Pebibyte); + + /// + /// Get Information in Petabits. + /// + public double Petabits => As(InformationUnit.Petabit); + + /// + /// Get Information in Petabytes. + /// + public double Petabytes => As(InformationUnit.Petabyte); + + /// + /// Get Information in Tebibits. + /// + public double Tebibits => As(InformationUnit.Tebibit); + + /// + /// Get Information in Tebibytes. + /// + public double Tebibytes => As(InformationUnit.Tebibyte); + + /// + /// Get Information in Terabits. + /// + public double Terabits => As(InformationUnit.Terabit); + + /// + /// Get Information in Terabytes. + /// + public double Terabytes => As(InformationUnit.Terabyte); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(InformationUnit 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(InformationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Information from Bits. + /// + /// If value is NaN or Infinity. + public static Information FromBits(QuantityValue bits) + { + decimal value = (decimal) bits; + return new Information(value, InformationUnit.Bit); + } + /// + /// Get Information from Bytes. + /// + /// If value is NaN or Infinity. + public static Information FromBytes(QuantityValue bytes) + { + decimal value = (decimal) bytes; + return new Information(value, InformationUnit.Byte); + } + /// + /// Get Information from Exabits. + /// + /// If value is NaN or Infinity. + public static Information FromExabits(QuantityValue exabits) + { + decimal value = (decimal) exabits; + return new Information(value, InformationUnit.Exabit); + } + /// + /// Get Information from Exabytes. + /// + /// If value is NaN or Infinity. + public static Information FromExabytes(QuantityValue exabytes) + { + decimal value = (decimal) exabytes; + return new Information(value, InformationUnit.Exabyte); + } + /// + /// Get Information from Exbibits. + /// + /// If value is NaN or Infinity. + public static Information FromExbibits(QuantityValue exbibits) + { + decimal value = (decimal) exbibits; + return new Information(value, InformationUnit.Exbibit); + } + /// + /// Get Information from Exbibytes. + /// + /// If value is NaN or Infinity. + public static Information FromExbibytes(QuantityValue exbibytes) + { + decimal value = (decimal) exbibytes; + return new Information(value, InformationUnit.Exbibyte); + } + /// + /// Get Information from Gibibits. + /// + /// If value is NaN or Infinity. + public static Information FromGibibits(QuantityValue gibibits) + { + decimal value = (decimal) gibibits; + return new Information(value, InformationUnit.Gibibit); + } + /// + /// Get Information from Gibibytes. + /// + /// If value is NaN or Infinity. + public static Information FromGibibytes(QuantityValue gibibytes) + { + decimal value = (decimal) gibibytes; + return new Information(value, InformationUnit.Gibibyte); + } + /// + /// Get Information from Gigabits. + /// + /// If value is NaN or Infinity. + public static Information FromGigabits(QuantityValue gigabits) + { + decimal value = (decimal) gigabits; + return new Information(value, InformationUnit.Gigabit); + } + /// + /// Get Information from Gigabytes. + /// + /// If value is NaN or Infinity. + public static Information FromGigabytes(QuantityValue gigabytes) + { + decimal value = (decimal) gigabytes; + return new Information(value, InformationUnit.Gigabyte); + } + /// + /// Get Information from Kibibits. + /// + /// If value is NaN or Infinity. + public static Information FromKibibits(QuantityValue kibibits) + { + decimal value = (decimal) kibibits; + return new Information(value, InformationUnit.Kibibit); + } + /// + /// Get Information from Kibibytes. + /// + /// If value is NaN or Infinity. + public static Information FromKibibytes(QuantityValue kibibytes) + { + decimal value = (decimal) kibibytes; + return new Information(value, InformationUnit.Kibibyte); + } + /// + /// Get Information from Kilobits. + /// + /// If value is NaN or Infinity. + public static Information FromKilobits(QuantityValue kilobits) + { + decimal value = (decimal) kilobits; + return new Information(value, InformationUnit.Kilobit); + } + /// + /// Get Information from Kilobytes. + /// + /// If value is NaN or Infinity. + public static Information FromKilobytes(QuantityValue kilobytes) + { + decimal value = (decimal) kilobytes; + return new Information(value, InformationUnit.Kilobyte); + } + /// + /// Get Information from Mebibits. + /// + /// If value is NaN or Infinity. + public static Information FromMebibits(QuantityValue mebibits) + { + decimal value = (decimal) mebibits; + return new Information(value, InformationUnit.Mebibit); + } + /// + /// Get Information from Mebibytes. + /// + /// If value is NaN or Infinity. + public static Information FromMebibytes(QuantityValue mebibytes) + { + decimal value = (decimal) mebibytes; + return new Information(value, InformationUnit.Mebibyte); + } + /// + /// Get Information from Megabits. + /// + /// If value is NaN or Infinity. + public static Information FromMegabits(QuantityValue megabits) + { + decimal value = (decimal) megabits; + return new Information(value, InformationUnit.Megabit); + } + /// + /// Get Information from Megabytes. + /// + /// If value is NaN or Infinity. + public static Information FromMegabytes(QuantityValue megabytes) + { + decimal value = (decimal) megabytes; + return new Information(value, InformationUnit.Megabyte); + } + /// + /// Get Information from Pebibits. + /// + /// If value is NaN or Infinity. + public static Information FromPebibits(QuantityValue pebibits) + { + decimal value = (decimal) pebibits; + return new Information(value, InformationUnit.Pebibit); + } + /// + /// Get Information from Pebibytes. + /// + /// If value is NaN or Infinity. + public static Information FromPebibytes(QuantityValue pebibytes) + { + decimal value = (decimal) pebibytes; + return new Information(value, InformationUnit.Pebibyte); + } + /// + /// Get Information from Petabits. + /// + /// If value is NaN or Infinity. + public static Information FromPetabits(QuantityValue petabits) + { + decimal value = (decimal) petabits; + return new Information(value, InformationUnit.Petabit); + } + /// + /// Get Information from Petabytes. + /// + /// If value is NaN or Infinity. + public static Information FromPetabytes(QuantityValue petabytes) + { + decimal value = (decimal) petabytes; + return new Information(value, InformationUnit.Petabyte); + } + /// + /// Get Information from Tebibits. + /// + /// If value is NaN or Infinity. + public static Information FromTebibits(QuantityValue tebibits) + { + decimal value = (decimal) tebibits; + return new Information(value, InformationUnit.Tebibit); + } + /// + /// Get Information from Tebibytes. + /// + /// If value is NaN or Infinity. + public static Information FromTebibytes(QuantityValue tebibytes) + { + decimal value = (decimal) tebibytes; + return new Information(value, InformationUnit.Tebibyte); + } + /// + /// Get Information from Terabits. + /// + /// If value is NaN or Infinity. + public static Information FromTerabits(QuantityValue terabits) + { + decimal value = (decimal) terabits; + return new Information(value, InformationUnit.Terabit); + } + /// + /// Get Information from Terabytes. + /// + /// If value is NaN or Infinity. + public static Information FromTerabytes(QuantityValue terabytes) + { + decimal value = (decimal) terabytes; + return new Information(value, InformationUnit.Terabyte); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Information unit value. + public static Information From(QuantityValue value, InformationUnit fromUnit) + { + return new Information((decimal)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", new CultureInfo("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 Information Parse(string str) + { + return ParseInternal(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", new CultureInfo("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 Information Parse(string str, [CanBeNull] IFormatProvider provider) + { + return ParseInternal(str, provider); + } - public partial struct Information : IQuantity, IComparable, IComparable - { /// - /// The numeric value this quantity was constructed with. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// - public decimal Value => _value; + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Information result) + { + return TryParseInternal(str, null, out result); + } /// - /// Get unit abbreviation string. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to if null. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) { - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + return TryParseInternal(str, provider, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static InformationUnit ParseUnit(string str) + { + return ParseUnitInternal(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static InformationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return ParseUnitInternal(str, provider); + } + + public static bool TryParseUnit(string str, out InformationUnit unit) + { + return TryParseUnitInternal(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", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out InformationUnit unit) + { + return TryParseUnitInternal(str, provider, out unit); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.Parse("5.5 m", new CultureInfo("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. + /// + private static Information ParseInternal(string str, [CanBeNull] IFormatProvider provider) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} + /// Format to use when parsing number and unit. Defaults to . + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) + { + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + private static InformationUnit ParseUnitInternal(string str, IFormatProvider provider = null) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse(str.Trim(), provider); + + if (unit == InformationUnit.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized InformationUnit."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out InformationUnit unit) + { + unit = InformationUnit.Undefined; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + if(!UnitParser.Default.TryParse(str.Trim(), provider, out unit)) + return false; + + if(unit == InformationUnit.Undefined) + return false; + + return true; } + #endregion + #region Arithmetic Operators public static Information operator -(Information right) @@ -106,6 +836,8 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(Information left, Information right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -126,91 +858,216 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - #region Parsing + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is Information)) throw new ArgumentException("Expected type Information.", nameof(obj)); + + return CompareTo((Information)obj); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Information other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// Compare equality to another Information within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// - /// Length.Parse("5.5 m", new CultureInfo("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 Information Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Information other, double tolerance, ComparisonType comparisonType) { - return ParseInternal(str, provider); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) + /// A hash code for the current Information. + public override int GetHashCode() { - return TryParseInternal(str, provider, out result); + return new { Value, Unit }.GetHashCode(); } + #endregion + + #region Conversion Methods + /// - /// Parse a unit string. + /// Convert to the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static InformationUnit ParseUnit(string str, IFormatProvider provider = null) + /// Value converted to the specified unit. + public double As(InformationUnit unit) { - return ParseUnitInternal(str, provider); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Information to another Information with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - public static bool TryParseUnit(string str, IFormatProvider provider, out InformationUnit unit) + /// A Information with the specified unit. + public Information ToUnit(InformationUnit unit) { - return TryParseUnitInternal(str, provider, out unit); + var convertedValue = AsBaseNumericType(unit); + return new Information(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 decimal AsBaseUnit() + { + switch(Unit) + { + case InformationUnit.Bit: return _value; + case InformationUnit.Byte: return _value*8m; + case InformationUnit.Exabit: return (_value) * 1e18m; + case InformationUnit.Exabyte: return (_value*8m) * 1e18m; + case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Exbibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); + case InformationUnit.Gibibyte: return (_value*8m) * (1024m * 1024 * 1024); + case InformationUnit.Gigabit: return (_value) * 1e9m; + case InformationUnit.Gigabyte: return (_value*8m) * 1e9m; + case InformationUnit.Kibibit: return (_value) * 1024m; + case InformationUnit.Kibibyte: return (_value*8m) * 1024m; + case InformationUnit.Kilobit: return (_value) * 1e3m; + case InformationUnit.Kilobyte: return (_value*8m) * 1e3m; + case InformationUnit.Mebibit: return (_value) * (1024m * 1024); + case InformationUnit.Mebibyte: return (_value*8m) * (1024m * 1024); + case InformationUnit.Megabit: return (_value) * 1e6m; + case InformationUnit.Megabyte: return (_value*8m) * 1e6m; + case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Pebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Petabit: return (_value) * 1e15m; + case InformationUnit.Petabyte: return (_value*8m) * 1e15m; + case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); + case InformationUnit.Tebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024); + case InformationUnit.Terabit: return (_value) * 1e12m; + case InformationUnit.Terabyte: return (_value*8m) * 1e12m; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private decimal AsBaseNumericType(InformationUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case InformationUnit.Bit: return baseUnitValue; + case InformationUnit.Byte: return baseUnitValue/8m; + case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; + case InformationUnit.Exabyte: return (baseUnitValue/8m) / 1e18m; + case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Exbibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); + case InformationUnit.Gibibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024); + case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; + case InformationUnit.Gigabyte: return (baseUnitValue/8m) / 1e9m; + case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; + case InformationUnit.Kibibyte: return (baseUnitValue/8m) / 1024m; + case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; + case InformationUnit.Kilobyte: return (baseUnitValue/8m) / 1e3m; + case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); + case InformationUnit.Mebibyte: return (baseUnitValue/8m) / (1024m * 1024); + case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; + case InformationUnit.Megabyte: return (baseUnitValue/8m) / 1e6m; + case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Pebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); + case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; + case InformationUnit.Petabyte: return (baseUnitValue/8m) / 1e15m; + case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); + case InformationUnit.Tebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); + case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; + case InformationUnit.Terabyte: return (baseUnitValue/8m) / 1e12m; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(Unit); + } + + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString(InformationUnit unit) + { + return ToString(unit, null, 2); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provider) { return ToString(unit, provider, 2); @@ -220,10 +1077,9 @@ public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provide /// Get string representation of value and unit. /// /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { double value = As(unit); @@ -234,12 +1090,11 @@ public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provide /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to if null. /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); @@ -253,5 +1108,6 @@ public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provide } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs index 02136fc7f6..1dc73d885a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs @@ -36,8 +36,11 @@ // THE SOFTWARE. using System; +using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -46,93 +49,488 @@ namespace UnitsNet /// /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. /// - // ReSharper disable once PartialTypeWithSinglePart - public partial struct Length : IQuantity, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LengthUnit? _unit; + + static Length() + { + BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Length(double numericValue, LengthUnit unit) + { + if(unit == LengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Length, which is Meter. All conversions go via this value. + /// + public static LengthUnit BaseUnit => LengthUnit.Meter; + + /// + /// Represents the largest possible value of Length + /// + public static Length MaxValue => new Length(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Length + /// + public static Length MinValue => new Length(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Length; + + /// + /// All units of measurement for the Length quantity. + /// + public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Meter. + /// + public static Length Zero => new Length(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Length.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Length.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Length in Centimeters. + /// + public double Centimeters => As(LengthUnit.Centimeter); + + /// + /// Get Length in Decimeters. + /// + public double Decimeters => As(LengthUnit.Decimeter); + + /// + /// Get Length in DtpPicas. + /// + public double DtpPicas => As(LengthUnit.DtpPica); + + /// + /// Get Length in DtpPoints. + /// + public double DtpPoints => As(LengthUnit.DtpPoint); + + /// + /// Get Length in Fathoms. + /// + public double Fathoms => As(LengthUnit.Fathom); + + /// + /// Get Length in Feet. + /// + public double Feet => As(LengthUnit.Foot); + + /// + /// Get Length in Inches. + /// + public double Inches => As(LengthUnit.Inch); + + /// + /// Get Length in Kilometers. + /// + public double Kilometers => As(LengthUnit.Kilometer); + + /// + /// Get Length in Meters. + /// + public double Meters => As(LengthUnit.Meter); + + /// + /// Get Length in Microinches. + /// + public double Microinches => As(LengthUnit.Microinch); + + /// + /// Get Length in Micrometers. + /// + public double Micrometers => As(LengthUnit.Micrometer); + + /// + /// Get Length in Mils. + /// + public double Mils => As(LengthUnit.Mil); + + /// + /// Get Length in Miles. + /// + public double Miles => As(LengthUnit.Mile); + + /// + /// Get Length in Millimeters. + /// + public double Millimeters => As(LengthUnit.Millimeter); + + /// + /// Get Length in Nanometers. + /// + public double Nanometers => As(LengthUnit.Nanometer); + + /// + /// Get Length in NauticalMiles. + /// + public double NauticalMiles => As(LengthUnit.NauticalMile); + + /// + /// Get Length in PrinterPicas. + /// + public double PrinterPicas => As(LengthUnit.PrinterPica); + + /// + /// Get Length in PrinterPoints. + /// + public double PrinterPoints => As(LengthUnit.PrinterPoint); + + /// + /// Get Length in Shackles. + /// + public double Shackles => As(LengthUnit.Shackle); + + /// + /// Get Length in Twips. + /// + public double Twips => As(LengthUnit.Twip); + + /// + /// Get Length in UsSurveyFeet. + /// + public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + + /// + /// Get Length in Yards. + /// + public double Yards => As(LengthUnit.Yard); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LengthUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to if null. /// Unit abbreviation string. - [UsedImplicitly] + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LengthUnit unit, [CanBeNull] IFormatProvider provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - #region Arithmetic Operators + #endregion - public static Length operator -(Length right) + #region Static Factory Methods + + /// + /// Get Length from Centimeters. + /// + /// If value is NaN or Infinity. + public static Length FromCentimeters(QuantityValue centimeters) { - return new Length(-right.Value, right.Unit); + double value = (double) centimeters; + return new Length(value, LengthUnit.Centimeter); } - - public static Length operator +(Length left, Length right) + /// + /// Get Length from Decimeters. + /// + /// If value is NaN or Infinity. + public static Length FromDecimeters(QuantityValue decimeters) { - return new Length(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + double value = (double) decimeters; + return new Length(value, LengthUnit.Decimeter); } - - public static Length operator -(Length left, Length right) + /// + /// Get Length from DtpPicas. + /// + /// If value is NaN or Infinity. + public static Length FromDtpPicas(QuantityValue dtppicas) { - return new Length(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + double value = (double) dtppicas; + return new Length(value, LengthUnit.DtpPica); } - - public static Length operator *(double left, Length right) + /// + /// Get Length from DtpPoints. + /// + /// If value is NaN or Infinity. + public static Length FromDtpPoints(QuantityValue dtppoints) { - return new Length(left * right.Value, right.Unit); + double value = (double) dtppoints; + return new Length(value, LengthUnit.DtpPoint); } - - public static Length operator *(Length left, double right) + /// + /// Get Length from Fathoms. + /// + /// If value is NaN or Infinity. + public static Length FromFathoms(QuantityValue fathoms) { - return new Length(left.Value * right, left.Unit); + double value = (double) fathoms; + return new Length(value, LengthUnit.Fathom); } - - public static Length operator /(Length left, double right) + /// + /// Get Length from Feet. + /// + /// If value is NaN or Infinity. + public static Length FromFeet(QuantityValue feet) { - return new Length(left.Value / right, left.Unit); + double value = (double) feet; + return new Length(value, LengthUnit.Foot); } - - public static double operator /(Length left, Length right) + /// + /// Get Length from Inches. + /// + /// If value is NaN or Infinity. + public static Length FromInches(QuantityValue inches) { - return left.Meters / right.Meters; + double value = (double) inches; + return new Length(value, LengthUnit.Inch); } - - #endregion - - public static bool operator <=(Length left, Length right) + /// + /// Get Length from Kilometers. + /// + /// If value is NaN or Infinity. + public static Length FromKilometers(QuantityValue kilometers) { - return left.Value <= right.AsBaseNumericType(left.Unit); + double value = (double) kilometers; + return new Length(value, LengthUnit.Kilometer); } - - public static bool operator >=(Length left, Length right) + /// + /// Get Length from Meters. + /// + /// If value is NaN or Infinity. + public static Length FromMeters(QuantityValue meters) { - return left.Value >= right.AsBaseNumericType(left.Unit); + double value = (double) meters; + return new Length(value, LengthUnit.Meter); } - - public static bool operator <(Length left, Length right) + /// + /// Get Length from Microinches. + /// + /// If value is NaN or Infinity. + public static Length FromMicroinches(QuantityValue microinches) { - return left.Value < right.AsBaseNumericType(left.Unit); + double value = (double) microinches; + return new Length(value, LengthUnit.Microinch); + } + /// + /// Get Length from Micrometers. + /// + /// If value is NaN or Infinity. + public static Length FromMicrometers(QuantityValue micrometers) + { + double value = (double) micrometers; + return new Length(value, LengthUnit.Micrometer); + } + /// + /// Get Length from Mils. + /// + /// If value is NaN or Infinity. + public static Length FromMils(QuantityValue mils) + { + double value = (double) mils; + return new Length(value, LengthUnit.Mil); + } + /// + /// Get Length from Miles. + /// + /// If value is NaN or Infinity. + public static Length FromMiles(QuantityValue miles) + { + double value = (double) miles; + return new Length(value, LengthUnit.Mile); + } + /// + /// Get Length from Millimeters. + /// + /// If value is NaN or Infinity. + public static Length FromMillimeters(QuantityValue millimeters) + { + double value = (double) millimeters; + return new Length(value, LengthUnit.Millimeter); + } + /// + /// Get Length from Nanometers. + /// + /// If value is NaN or Infinity. + public static Length FromNanometers(QuantityValue nanometers) + { + double value = (double) nanometers; + return new Length(value, LengthUnit.Nanometer); + } + /// + /// Get Length from NauticalMiles. + /// + /// If value is NaN or Infinity. + public static Length FromNauticalMiles(QuantityValue nauticalmiles) + { + double value = (double) nauticalmiles; + return new Length(value, LengthUnit.NauticalMile); + } + /// + /// Get Length from PrinterPicas. + /// + /// If value is NaN or Infinity. + public static Length FromPrinterPicas(QuantityValue printerpicas) + { + double value = (double) printerpicas; + return new Length(value, LengthUnit.PrinterPica); + } + /// + /// Get Length from PrinterPoints. + /// + /// If value is NaN or Infinity. + public static Length FromPrinterPoints(QuantityValue printerpoints) + { + double value = (double) printerpoints; + return new Length(value, LengthUnit.PrinterPoint); + } + /// + /// Get Length from Shackles. + /// + /// If value is NaN or Infinity. + public static Length FromShackles(QuantityValue shackles) + { + double value = (double) shackles; + return new Length(value, LengthUnit.Shackle); + } + /// + /// Get Length from Twips. + /// + /// If value is NaN or Infinity. + public static Length FromTwips(QuantityValue twips) + { + double value = (double) twips; + return new Length(value, LengthUnit.Twip); + } + /// + /// Get Length from UsSurveyFeet. + /// + /// If value is NaN or Infinity. + public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) + { + double value = (double) ussurveyfeet; + return new Length(value, LengthUnit.UsSurveyFoot); + } + /// + /// Get Length from Yards. + /// + /// If value is NaN or Infinity. + public static Length FromYards(QuantityValue yards) + { + double value = (double) yards; + return new Length(value, LengthUnit.Yard); } - public static bool operator >(Length left, Length right) + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Length unit value. + public static Length From(QuantityValue value, LengthUnit fromUnit) { - return left.Value > right.AsBaseNumericType(left.Unit); + return new Length((double)value, fromUnit); } - #region Parsing + #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", new CultureInfo("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 Length Parse(string str) + { + return ParseInternal(str, null); + } /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -151,6 +549,7 @@ public static string GetAbbreviation(LengthUnit unit, [CanBeNull] IFormatProvide /// 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 Length Parse(string str, [CanBeNull] IFormatProvider provider) { return ParseInternal(str, provider); @@ -160,12 +559,25 @@ public static Length Parse(string str, [CanBeNull] IFormatProvider provider) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Length result) + { + return TryParseInternal(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", new CultureInfo("en-US")); /// + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Length result) { return TryParseInternal(str, provider, out result); @@ -175,42 +587,423 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider /// 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", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + public static LengthUnit ParseUnit(string str) + { + return ParseUnitInternal(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. public static LengthUnit ParseUnit(string str, IFormatProvider provider = null) { return ParseUnitInternal(str, provider); } + public static bool TryParseUnit(string str, out LengthUnit unit) + { + return TryParseUnitInternal(str, null, out unit); + } + /// /// 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. /// The parsed unit if successful. /// True if successful, otherwise false. /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider provider, out LengthUnit unit) { return TryParseUnitInternal(str, provider, out unit); } + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.Parse("5.5 m", new CultureInfo("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. + /// + private static Length ParseInternal(string str, [CanBeNull] IFormatProvider provider) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} + /// Format to use when parsing number and unit. Defaults to . + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Length result) + { + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + private static LengthUnit ParseUnitInternal(string str, IFormatProvider provider = null) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse(str.Trim(), provider); + + if (unit == LengthUnit.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LengthUnit."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LengthUnit unit) + { + unit = LengthUnit.Undefined; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + if(!UnitParser.Default.TryParse(str.Trim(), provider, out unit)) + return false; + + if(unit == LengthUnit.Undefined) + return false; + + return true; + } + + #endregion + + #region Arithmetic Operators + + public static Length operator -(Length right) + { + return new Length(-right.Value, right.Unit); + } + + public static Length operator +(Length left, Length right) + { + return new Length(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Length operator -(Length left, Length right) + { + return new Length(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Length operator *(double left, Length right) + { + return new Length(left * right.Value, right.Unit); + } + + public static Length operator *(Length left, double right) + { + return new Length(left.Value * right, left.Unit); + } + + public static Length operator /(Length left, double right) + { + return new Length(left.Value / right, left.Unit); + } + + public static double operator /(Length left, Length right) + { + return left.Meters / right.Meters; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Length left, Length right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Length left, Length right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Length left, Length right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Length left, Length right) + { + return left.Value > right.AsBaseNumericType(left.Unit); + } + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is Length)) throw new ArgumentException("Expected type Length.", nameof(obj)); + + return CompareTo((Length)obj); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Length other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another Length within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Length other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Length. + public override int GetHashCode() + { + return new { Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Length to another Length with the unit representation . + /// + /// A Length with the specified unit. + public Length ToUnit(LengthUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Length(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 AsBaseUnit() + { + switch(Unit) + { + case LengthUnit.Centimeter: return (_value) * 1e-2d; + case LengthUnit.Decimeter: return (_value) * 1e-1d; + case LengthUnit.DtpPica: return _value/236.220472441; + case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; + case LengthUnit.Fathom: return _value*1.8288; + case LengthUnit.Foot: return _value*0.3048; + case LengthUnit.Inch: return _value*2.54e-2; + case LengthUnit.Kilometer: return (_value) * 1e3d; + case LengthUnit.Meter: return _value; + case LengthUnit.Microinch: return _value*2.54e-8; + case LengthUnit.Micrometer: return (_value) * 1e-6d; + case LengthUnit.Mil: return _value*2.54e-5; + case LengthUnit.Mile: return _value*1609.34; + case LengthUnit.Millimeter: return (_value) * 1e-3d; + case LengthUnit.Nanometer: return (_value) * 1e-9d; + case LengthUnit.NauticalMile: return _value*1852; + case LengthUnit.PrinterPica: return _value/237.106301584; + case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; + case LengthUnit.Shackle: return _value*27.432; + case LengthUnit.Twip: return _value/56692.913385826; + case LengthUnit.UsSurveyFoot: return _value*1200/3937; + case LengthUnit.Yard: return _value*0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(LengthUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; + case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; + case LengthUnit.DtpPica: return baseUnitValue*236.220472441; + case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; + case LengthUnit.Fathom: return baseUnitValue/1.8288; + case LengthUnit.Foot: return baseUnitValue/0.3048; + case LengthUnit.Inch: return baseUnitValue/2.54e-2; + case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; + case LengthUnit.Meter: return baseUnitValue; + case LengthUnit.Microinch: return baseUnitValue/2.54e-8; + case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; + case LengthUnit.Mil: return baseUnitValue/2.54e-5; + case LengthUnit.Mile: return baseUnitValue/1609.34; + case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; + case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; + case LengthUnit.NauticalMile: return baseUnitValue/1852; + case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; + case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; + case LengthUnit.Shackle: return baseUnitValue/27.432; + case LengthUnit.Twip: return baseUnitValue*56692.913385826; + case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; + case LengthUnit.Yard: return baseUnitValue/0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(Unit); + } + + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString(LengthUnit unit) + { + return ToString(unit, null, 2); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider) { return ToString(unit, provider, 2); @@ -220,10 +1013,9 @@ public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider) /// Get string representation of value and unit. /// /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { double value = As(unit); @@ -234,12 +1026,11 @@ public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider, in /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to if null. /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); @@ -253,5 +1044,6 @@ public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider, [N } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs index 92fb22feab..0029fb65aa 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs @@ -36,8 +36,11 @@ // THE SOFTWARE. using System; +using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -46,101 +49,314 @@ namespace UnitsNet /// /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// - // ReSharper disable once PartialTypeWithSinglePart - public partial struct Level : IQuantity, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LevelUnit? _unit; + + static Level() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Level(double numericValue, LevelUnit unit) + { + if(unit == LevelUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Level, which is Decibel. All conversions go via this value. + /// + public static LevelUnit BaseUnit => LevelUnit.Decibel; + + /// + /// Represents the largest possible value of Level + /// + public static Level MaxValue => new Level(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Level + /// + public static Level MinValue => new Level(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Level; + + /// + /// All units of measurement for the Level quantity. + /// + public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. + /// + public static Level Zero => new Level(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Level.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Level.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Level in Decibels. + /// + public double Decibels => As(LevelUnit.Decibel); + + /// + /// Get Level in Nepers. + /// + public double Nepers => As(LevelUnit.Neper); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LevelUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to if null. /// Unit abbreviation string. - [UsedImplicitly] + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LevelUnit unit, [CanBeNull] IFormatProvider provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - #region Logarithmic Arithmetic Operators + #endregion - public static Level operator -(Level right) + #region Static Factory Methods + + /// + /// Get Level from Decibels. + /// + /// If value is NaN or Infinity. + public static Level FromDecibels(QuantityValue decibels) { - return new Level(-right.Value, right.Unit); + double value = (double) decibels; + return new Level(value, LevelUnit.Decibel); } - - public static Level operator +(Level left, Level right) + /// + /// Get Level from Nepers. + /// + /// If value is NaN or Infinity. + public static Level FromNepers(QuantityValue nepers) { - // Logarithmic addition - // Formula: 10*log10(10^(x/10) + 10^(y/10)) - return new Level(10*Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); + double value = (double) nepers; + return new Level(value, LevelUnit.Neper); } - public static Level operator -(Level left, Level right) + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Level unit value. + public static Level From(QuantityValue value, LevelUnit fromUnit) { - // Logarithmic subtraction - // Formula: 10*log10(10^(x/10) - 10^(y/10)) - return new Level(10*Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); + return new Level((double)value, fromUnit); } - public static Level operator *(double left, Level right) + #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", new CultureInfo("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 Level Parse(string str) { - // Logarithmic multiplication = addition - return new Level(left + right.Value, right.Unit); + return ParseInternal(str, null); } - public static Level operator *(Level left, double right) + /// + /// 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", new CultureInfo("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 Level Parse(string str, [CanBeNull] IFormatProvider provider) { - // Logarithmic multiplication = addition - return new Level(left.Value + (double)right, left.Unit); + return ParseInternal(str, provider); } - public static Level operator /(Level left, double right) + /// + /// 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", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Level result) { - // Logarithmic division = subtraction - return new Level(left.Value - (double)right, left.Unit); + return TryParseInternal(str, null, out result); } - public static double operator /(Level left, Level right) + /// + /// 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", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) { - // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); + return TryParseInternal(str, provider, out result); } - #endregion - - public static bool operator <=(Level left, Level right) + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static LevelUnit ParseUnit(string str) { - return left.Value <= right.AsBaseNumericType(left.Unit); + return ParseUnitInternal(str, null); } - public static bool operator >=(Level left, Level right) + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static LevelUnit ParseUnit(string str, IFormatProvider provider = null) { - return left.Value >= right.AsBaseNumericType(left.Unit); + return ParseUnitInternal(str, provider); } - public static bool operator <(Level left, Level right) + public static bool TryParseUnit(string str, out LevelUnit unit) { - return left.Value < right.AsBaseNumericType(left.Unit); + return TryParseUnitInternal(str, null, out unit); } - public static bool operator >(Level left, Level right) + /// + /// 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", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out LevelUnit unit) { - return left.Value > right.AsBaseNumericType(left.Unit); + return TryParseUnitInternal(str, provider, out unit); } - #region Parsing - /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to . /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -159,66 +375,323 @@ public static string GetAbbreviation(LevelUnit unit, [CanBeNull] IFormatProvider /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Level Parse(string str, [CanBeNull] IFormatProvider provider) + private static Level ParseInternal(string str, [CanBeNull] IFormatProvider provider) { - return ParseInternal(str, provider); + if (str == null) throw new ArgumentNullException(nameof(str)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to . /// Resulting unit quantity if successful. /// True if successful, otherwise false. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) { - return TryParseInternal(str, provider, out result); + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse(str, provider, TryParseUnitInternal, From, out result); } /// /// 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. + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LevelUnit ParseUnit(string str, IFormatProvider provider = null) + private static LevelUnit ParseUnitInternal(string str, IFormatProvider provider = null) { - return ParseUnitInternal(str, provider); + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse(str.Trim(), provider); + + if (unit == LevelUnit.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LevelUnit."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; } /// /// 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. + /// Format to use when parsing number and unit. Defaults to . /// The parsed unit if successful. /// True if successful, otherwise false. /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// Length.ParseUnit("m", new CultureInfo("en-US")); /// - public static bool TryParseUnit(string str, IFormatProvider provider, out LevelUnit unit) + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out LevelUnit unit) { - return TryParseUnitInternal(str, provider, out unit); + unit = LevelUnit.Undefined; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + if(!UnitParser.Default.TryParse(str.Trim(), provider, out unit)) + return false; + + if(unit == LevelUnit.Undefined) + return false; + + return true; + } + + #endregion + + #region Logarithmic Arithmetic Operators + + public static Level operator -(Level right) + { + return new Level(-right.Value, right.Unit); + } + + public static Level operator +(Level left, Level right) + { + // Logarithmic addition + // Formula: 10*log10(10^(x/10) + 10^(y/10)) + return new Level(10*Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); + } + + public static Level operator -(Level left, Level right) + { + // Logarithmic subtraction + // Formula: 10*log10(10^(x/10) - 10^(y/10)) + return new Level(10*Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); + } + + public static Level operator *(double left, Level right) + { + // Logarithmic multiplication = addition + return new Level(left + right.Value, right.Unit); + } + + public static Level operator *(Level left, double right) + { + // Logarithmic multiplication = addition + return new Level(left.Value + (double)right, left.Unit); + } + + public static Level operator /(Level left, double right) + { + // Logarithmic division = subtraction + return new Level(left.Value - (double)right, left.Unit); + } + + public static double operator /(Level left, Level right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Level left, Level right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Level left, Level right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Level left, Level right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Level left, Level right) + { + return left.Value > right.AsBaseNumericType(left.Unit); + } + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is Level)) throw new ArgumentException("Expected type Level.", nameof(obj)); + + return CompareTo((Level)obj); + } + + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Level other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another Level within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Level other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Level. + public override int GetHashCode() + { + return new { Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LevelUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Level to another Level with the unit representation . + /// + /// A Level with the specified unit. + public Level ToUnit(LevelUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Level(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 AsBaseUnit() + { + switch(Unit) + { + case LevelUnit.Decibel: return _value; + case LevelUnit.Neper: return (1/0.115129254)*_value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(LevelUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case LevelUnit.Decibel: return baseUnitValue; + case LevelUnit.Neper: return 0.115129254*baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(Unit); + } + + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString(LevelUnit unit) + { + return ToString(unit, null, 2); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider) { return ToString(unit, provider, 2); @@ -228,10 +701,9 @@ public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider) /// Get string representation of value and unit. /// /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { double value = As(unit); @@ -242,12 +714,11 @@ public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider, int /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to if null. /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); @@ -261,5 +732,6 @@ public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider, [No } #endregion + } } diff --git a/UnitsNet/Scripts/GenerateUnits.ps1 b/UnitsNet/Scripts/GenerateUnits.ps1 index 4a8b0736db..e6750b5669 100644 --- a/UnitsNet/Scripts/GenerateUnits.ps1 +++ b/UnitsNet/Scripts/GenerateUnits.ps1 @@ -1,4 +1,8 @@ -# Set Write-Output used by Include- files to UTF8 encoding to fix copyright character +using module ".\Types.psm1" + +#Requires -Version 5.1 + +# Set Write-Output used by Include- files to UTF8 encoding to fix copyright character [Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8 $OutputEncoding = [Text.UTF8Encoding]::UTF8 @@ -8,32 +12,24 @@ function ToCamelCase($str) return $str.Substring(0,1).ToLowerInvariant() + $str.Substring(1) } +function ValueOrDefault($value, $defaultValue){ + if ($value -ne $null) { $value } else { $defaultValue } +} -function GenerateQuantity($quantity, $outDir) +function GenerateQuantity([Quantity]$quantity, $outDir) { - $outFileName = "$outDir/../../../Common/GeneratedCode/Quantities/$($quantity.Name).Common.g.cs" - GenerateQuantitySourceCodeCommon $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null - if (!$?) { - exit 1 - } - Write-Host -NoNewline "quantity common(OK) " - $outFileName = "$outDir/$($quantity.Name).NetFramework.g.cs" - GenerateQuantitySourceCodeNetFramework $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null - if (!$?) { - exit 1 - } + GenerateQuantitySourceCodeNetFramework $quantity "NetFramework" | Out-File -Encoding "UTF8" $outFileName | Out-Null + if (!$?) { exit 1 } Write-Host -NoNewline "quantity .NET(OK) " $outFileName = "$outDir/../../../UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/$($quantity.Name).WindowsRuntimeComponent.g.cs" - GenerateQuantitySourceCodeWindowsRuntimeComponent $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null - if (!$?) { - exit 1 - } + GenerateQuantitySourceCodeNetFramework $quantity "WindowsRuntimeComponent" | Out-File -Encoding "UTF8" $outFileName | Out-Null + if (!$?) { exit 1 } Write-Host -NoNewline "quantity WRC(OK) " } -function GenerateUnitTestBaseClass($quantity, $outDir) +function GenerateUnitTestBaseClass([Quantity]$quantity, $outDir) { $outFileName = "$outDir/$($quantity.Name)TestsBase.g.cs" GenerateUnitTestBaseClassSourceCode $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null @@ -43,7 +39,7 @@ function GenerateUnitTestBaseClass($quantity, $outDir) Write-Host -NoNewline "test base(OK) " } -function GenerateUnitTestClassIfNotExists($quantity, $outDir) +function GenerateUnitTestClassIfNotExists([Quantity]$quantity, $outDir) { Write-Host -NoNewline "test stub" $outFileName = "$outDir/$($quantity.Name)Tests.cs" @@ -62,7 +58,7 @@ function GenerateUnitTestClassIfNotExists($quantity, $outDir) } } -function GenerateUnitType($quantity, $outDir) +function GenerateUnitType([Quantity]$quantity, $outDir) { $outFileName = "$outDir/$($quantity.Name)Unit.g.cs" @@ -106,26 +102,6 @@ function EnsureDirExists([String] $dirPath) { } } -function Set-DefaultValues { - param ([Parameter(Mandatory = $true, ValueFromPipeline=$true)] $quantity) - PROCESS { - if (!$quantity.BaseType) { - $quantity | Add-Member BaseType "double" - } - if ($quantity.GenerateArithmetic -eq $null) { - $quantity | Add-Member GenerateArithmetic $true - } - # 'Logarithmic' is optional in the .json file and assumed to be false if not specified - if (!$quantity.Logarithmic) { - $quantity | Add-Member Logarithmic $false - } - elseif (!$quantity.LogarithmicScalingFactor) { - $quantity | Add-Member LogarithmicScalingFactor 1 - } - return $quantity - } -} - function Set-ConversionFunctions { param ([Parameter(Mandatory = $true, ValueFromPipeline=$true)] $quantity) @@ -230,7 +206,7 @@ function Set-UnitsOrderedByName { } } -function Add-InheritedUnits($quantity, $quantities) { +function Add-InheritedUnits([Quantity]$quantity, $quantities) { foreach ($inheritFromQuantityName in $quantity.InheritUnitsFrom) { $inheritFromQuantity = $quantities | Where { $_.Name -eq $inheritFromQuantityName } | Select -First 1 @@ -242,12 +218,9 @@ function Add-InheritedUnits($quantity, $quantities) { # Load external generator functions with same name as file . "$PSScriptRoot/Include-GenerateTemplates.ps1" -. "$PSScriptRoot/Include-GenerateLogarithmicCode.ps1" . "$PSScriptRoot/Include-GenerateUnitSystemDefaultSourceCode.ps1" . "$PSScriptRoot/Include-GenerateQuantityTypeSourceCode.ps1" -. "$PSScriptRoot/Include-GenerateQuantitySourceCodeCommon.ps1" . "$PSScriptRoot/Include-GenerateQuantitySourceCodeNetFramework.ps1" -. "$PSScriptRoot/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1" . "$PSScriptRoot/Include-GenerateUnitTypeSourceCode.ps1" . "$PSScriptRoot/Include-GenerateUnitTestBaseClassSourceCode.ps1" . "$PSScriptRoot/Include-GenerateUnitTestPlaceholderSourceCode.ps1" @@ -261,11 +234,54 @@ EnsureDirExists ($testsCustomCodeDir = "$PSScriptRoot/../../UnitsNet.Tests/Custo $templatesDir = "$PSScriptRoot/../../Common/UnitDefinitions" $pad = 25 -# Parse unit definitions from .json files and populate properties +# Parse unit definitions from .json files +# TODO Find a way to automap from JSON into Quantity type $quantities = Get-ChildItem -Path $templatesDir -filter "*.json" ` | %{(Get-Content $_.FullName -Encoding "UTF8" | Out-String)} ` | ConvertFrom-Json ` - | Set-DefaultValues ` + | %{ + # $_ | fl | out-string | write-host -foreground blue + # New-Object -TypeName Quantity -Verbose -Property @{ + [Quantity]@{ + Name = $_.Name + XmlDocSummary = $_.XmlDoc + XmlDocRemarks = $_.XmlDocRemarks + BaseUnit = $_.BaseUnit + BaseType = ValueOrDefault $_.BaseType "double" + BaseDimensions = @{ + Length = ValueOrDefault $_.BaseDimensions.L 0 + Mass = ValueOrDefault $_.BaseDimensions.M 0 + Time = ValueOrDefault $_.BaseDimensions.T 0 + ElectricCurrent = ValueOrDefault $_.BaseDimensions.I 0 + Temperature = ValueOrDefault $_.BaseDimensions.Θ 0 + AmountOfSubstance = ValueOrDefault $_.BaseDimensions.N 0 + LuminousIntensity = ValueOrDefault $_.BaseDimensions.J 0 + } + GenerateArithmetic = ValueOrDefault $_.GenerateArithmetic $true + Logarithmic = ValueOrDefault $_.Logarithmic $false + LogarithmicScalingFactor = ValueOrDefault $_.LogarithmicScalingFactor 1 + Units = $_.Units | %{ + # $_ | fl | out-string | Write-Host -ForegroundColor blue + [Unit]@{ + SingularName = $_.SingularName + PluralName = $_.PluralName + XmlDocSummary = $_.XmlDocSummary + XmlDocRemarks = $_.XmlDocRemarks + FromUnitToBaseFunc = $_.FromUnitToBaseFunc + FromBaseToUnitFunc = $_.FromBaseToUnitFunc + Prefixes = [string[]](ValueOrDefault $_.Prefixes @()) + Localization = $_.Localization | %{ + # $_ | fl | out-string | Write-Host -ForegroundColor blue + [Localization]@{ + Culture = $_.Culture + Abbreviations = $_.Abbreviations + AbbreviationsWithPrefixes = $_.AbbreviationsWithPrefixes + } + } + } + } + } + } ` | Add-PrefixUnits ` | Set-ConversionFunctions ` | Set-UnitsOrderedByName diff --git a/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 b/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 deleted file mode 100644 index ba7a62c49f..0000000000 --- a/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 +++ /dev/null @@ -1,72 +0,0 @@ -<# -.SYNOPSIS -Generates the C# source code for logarithmic arithmetic operators. - -.PARAMETER quantityName -The name of the unit. - -.PARAMETER baseUnitFieldName -The name of the backing field used to store the unit's value. - -.PARAMETER baseType -The data type of the backing field used to store the unit's value. - -.PARAMETER scalingFactor -The scaling factor used in logarithmic calculations. In most cases this is equal to 1. -#> -function GenerateLogarithmicArithmeticOperators([string]$quantityName, [string]$baseUnitFieldName, [string]$baseType, [int]$scalingFactor) -{ - # Most logarithmic operators need a simple scaling factor of 10. However, certain units such as voltage ratio need to - # use 20 instead of 10. - $x = 10 * $scalingFactor; - -@" - - #region Logarithmic Arithmetic Operators - - public static $quantityName operator -($quantityName right) - { - return new $quantityName(-right.Value, right.Unit); - } - - public static $quantityName operator +($quantityName left, $quantityName right) - { - // Logarithmic addition - // Formula: $x*log10(10^(x/$x) + 10^(y/$x)) - return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); - } - - public static $quantityName operator -($quantityName left, $quantityName right) - { - // Logarithmic subtraction - // Formula: $x*log10(10^(x/$x) - 10^(y/$x)) - return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); - } - - public static $quantityName operator *($baseType left, $quantityName right) - { - // Logarithmic multiplication = addition - return new $quantityName(left + right.Value, right.Unit); - } - - public static $quantityName operator *($quantityName left, double right) - { - // Logarithmic multiplication = addition - return new $quantityName(left.Value + ($baseType)right, left.Unit); - } - - public static $quantityName operator /($quantityName left, double right) - { - // Logarithmic division = subtraction - return new $quantityName(left.Value - ($baseType)right, left.Unit); - } - - public static double operator /($quantityName left, $quantityName right) - { - // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); - } - - #endregion -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 deleted file mode 100644 index 1ac1d02089..0000000000 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 +++ /dev/null @@ -1,603 +0,0 @@ -function GenerateQuantitySourceCodeCommon($quantity) -{ - $quantityName = $quantity.Name; - $units = $quantity.Units; - $baseType = $quantity.BaseType; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } - $baseUnitSingularName = $baseUnit.SingularName - $baseUnitPluralName = $baseUnit.PluralName - $unitEnumName = "$quantityName" + "Unit" - - # Base dimensions - $baseDimensions = $quantity.BaseDimensions; - $baseDimensionLength = if($baseDimensions.L){$baseDimensions.L} else{0}; - $baseDimensionMass = if($baseDimensions.M){$baseDimensions.M} else{0}; - $baseDimensionTime = if($baseDimensions.T){$baseDimensions.T} else{0}; - $baseDimensionElectricCurrent = if($baseDimensions.I){$baseDimensions.I} else{0}; - $baseDimensionTemperature = if($baseDimensions.Θ){$baseDimensions.Θ} else{0}; - $baseDimensionAmountOfSubstance = if($baseDimensions.N){$baseDimensions.N} else{0}; - $baseDimensionLuminousIntensity = if($baseDimensions.J){$baseDimensions.J} else{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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ -"@; -$obsoleteAttribute = GetObsoleteAttribute($quantity); -if ($obsoleteAttribute) -{ - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this section -} -@" - /// - /// $($quantity.XmlDoc) - /// - // ReSharper disable once PartialTypeWithSinglePart$($obsoleteAttribute) - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class $quantityName : IQuantity -#else - public partial struct $quantityName : IQuantity, IComparable, IComparable<$quantityName> -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly $baseType _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly $($unitEnumName)? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public $unitEnumName Unit => _unit.GetValueOrDefault(BaseUnit); - - static $quantityName() - { -"@; - if($baseDimensions) - { -@" - BaseDimensions = new BaseDimensions($baseDimensionLength, $baseDimensionMass, $baseDimensionTime, $baseDimensionElectricCurrent, $baseDimensionTemperature, $baseDimensionAmountOfSubstance, $baseDimensionLuminousIntensity); -"@; - } -@" - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to contruct this quantity with. - /// The unit representation to contruct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. -#if WINDOWS_UWP - private -#else - public -#endif - $quantityName($baseType numericValue, $unitEnumName unit) - { - if(unit == $unitEnumName.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - -"@; if ($quantity.BaseType -eq "double") {@" - _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); -"@; } else {@" - _value = numericValue; -"@; }@" - _unit = unit; - } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.$quantityName; - - /// - /// The base unit of $quantityName, which is $baseUnitSingularName. All conversions go via this value. - /// - public static $unitEnumName BaseUnit => $unitEnumName.$baseUnitSingularName; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the $quantityName quantity. - /// - public static $unitEnumName[] Units { get; } = Enum.GetValues(typeof($unitEnumName)).Cast<$unitEnumName>().Except(new $unitEnumName[]{ $unitEnumName.Undefined }).ToArray(); -"@; - foreach ($unit in $units) { - $propertyName = $unit.PluralName; - $obsoleteAttribute = GetObsoleteAttribute($unit); - if ($obsoleteAttribute) - { - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page - } -@" - - /// - /// Get $quantityName in $propertyName. - /// $($obsoleteAttribute) - public double $propertyName => As($unitEnumName.$($unit.SingularName)); -"@; }@" - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit $baseUnitSingularName. - /// - public static $quantityName Zero => new $quantityName(0, BaseUnit); - -"@; foreach ($unit in $units) { - $valueParamName = $unit.PluralName.ToLowerInvariant(); - $obsoleteAttribute = GetObsoleteAttribute($unit); - if ($obsoleteAttribute) - { - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page - } -@" - /// - /// Get $quantityName from $($unit.PluralName). - /// $($obsoleteAttribute) - /// If value is NaN or Infinity. -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static $quantityName From$($unit.PluralName)(double $valueParamName) -#else - public static $quantityName From$($unit.PluralName)(QuantityValue $valueParamName) -#endif - { - $baseType value = ($baseType) $valueParamName; - return new $quantityName(value, $unitEnumName.$($unit.SingularName)); - } - -"@; }@" - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// $quantityName unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static $quantityName From(double value, $unitEnumName fromUnit) -#else - public static $quantityName From(QuantityValue value, $unitEnumName fromUnit) -#endif - { - return new $quantityName(($baseType)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is $quantityName)) throw new ArgumentException("Expected type $quantityName.", nameof(obj)); - - return CompareTo(($quantityName)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo($quantityName other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another $quantityName within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals($quantityName other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current $quantityName. - public override int GetHashCode() - { - return new { Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As($unitEnumName unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this $quantityName to another $quantityName with the unit representation . - /// - /// A $quantityName with the specified unit. - public $quantityName ToUnit($unitEnumName unit) - { - var convertedValue = AsBaseNumericType(unit); - return new $quantityName(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 $baseType AsBaseUnit() - { - switch(Unit) - { -"@; foreach ($unit in $units) { - $func = $unit.FromUnitToBaseFunc.Replace("x", "_value");@" - case $unitEnumName.$($unit.SingularName): return $func; -"@; }@" - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private $baseType AsBaseNumericType($unitEnumName unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { -"@; foreach ($unit in $units) { - $func = $unit.FromBaseToUnitFunc.Replace("x", "baseUnitValue");@" - case $unitEnumName.$($unit.SingularName): return $func; -"@; }@" - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// 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", new CultureInfo("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 $quantityName Parse(string str) - { - return ParseInternal(str, null); - } - - /// - /// 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", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out $quantityName result) - { - return TryParseInternal(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static $unitEnumName ParseUnit(string str) - { - return ParseUnitInternal(str, null); - } - - public static bool TryParseUnit(string str, out $unitEnumName unit) - { - return TryParseUnitInternal(str, null, out unit); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("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. - /// - private static $quantityName ParseInternal(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.Parse<$quantityName, $unitEnumName>(str, provider, ParseUnitInternal, 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} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out $quantityName result) - { - result = default($quantityName); - - if(string.IsNullOrWhiteSpace(str)) - return false; - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - return QuantityParser.Default.TryParse<$quantityName, $unitEnumName>(str, provider, TryParseUnitInternal, From, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - private static $unitEnumName ParseUnitInternal(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unit = UnitParser.Default.Parse<$unitEnumName>(str, provider); - - if (unit == $unitEnumName.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized $unitEnumName."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - private static bool TryParseUnitInternal(string str, IFormatProvider provider, out $unitEnumName unit) - { - unit = $unitEnumName.Undefined; - - if(string.IsNullOrWhiteSpace(str)) - return false; - - if(!UnitParser.Default.TryParse<$unitEnumName>(str, provider, out unit)) - return false; - - if(unit == $unitEnumName.Undefined) - return false; - - return true; - } - - #endregion - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString($unitEnumName unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of $quantityName - /// - public static $quantityName MaxValue => new $quantityName($baseType.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of $quantityName - /// - public static $quantityName MinValue => new $quantityName($baseType.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => $quantityName.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => $quantityName.BaseDimensions; - } -} -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 index 050d62b676..a2e693f463 100644 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 +++ b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 @@ -1,14 +1,33 @@ -function GenerateQuantitySourceCodeNetFramework($quantity) +using module ".\Types.psm1" + +class GeneratorArgs +{ + [Quantity]$Quantity + [Unit]$BaseUnit + [string]$UnitEnumName + [boolean]$TargetIsWindowsRuntimeComponent +} + +function GenerateQuantitySourceCodeNetFramework([Quantity]$quantity, [string]$target) { $quantityName = $quantity.Name; $units = $quantity.Units; - $baseType = $quantity.BaseType; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } + $valueType = $quantity.BaseType; + [Unit]$baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } | Select-Object -First 1 $baseUnitSingularName = $baseUnit.SingularName $baseUnitPluralName = $baseUnit.PluralName - $baseUnitPluralNameLower = $baseUnitPluralName.ToLowerInvariant() $unitEnumName = "$quantityName" + "Unit" + $wrc = $target -eq "WindowsRuntimeComponent" + $privateAccessModifierIfWrc = if ($wrc) { "private" } else { "public" } + $baseDimensions = $quantity.BaseDimensions; + [GeneratorArgs]$genArgs = New-Object GeneratorArgs -Property @{ + Quantity = $quantity; + BaseUnit = $baseUnit; + UnitEnumName = $unitEnumName; + TargetIsWindowsRuntimeComponent = $wrc; + } + # $genArgs | fl | out-string | write-host -foreground yellow @" //------------------------------------------------------------------------------ // @@ -48,110 +67,440 @@ // THE SOFTWARE. using System; +using System.Globalization; +using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace namespace UnitsNet { +"@; +$obsoleteAttribute = GetObsoleteAttribute($quantity); +if ($obsoleteAttribute) +{ + $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this section +}@" /// - /// $($quantity.XmlDoc) + /// $($quantity.XmlDocSummary) /// - // ReSharper disable once PartialTypeWithSinglePart - +"@; if ($quantity.XmlDocRemarks) {@" + /// + /// $($quantity.XmlDocRemarks) + /// +"@; } + if($wrc) {@" + // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components + // Public structures can't have any members other than public fields, and those fields must be value types or strings. + // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. + public sealed partial class $quantityName : IQuantity +"@; } else {@" public partial struct $quantityName : IQuantity<$unitEnumName>, IComparable, IComparable<$quantityName> +"@; }@" { /// /// The numeric value this quantity was constructed with. /// - public $baseType Value => _value; + private readonly $valueType _value; /// - /// Get unit abbreviation string. + /// The unit this quantity was constructed with. /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to if null. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit, [CanBeNull] IFormatProvider provider) + private readonly $($unitEnumName)? _unit; + + static $quantityName() { - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); +"@; if($baseDimensions) + {@" + BaseDimensions = new BaseDimensions($($baseDimensions.Length), $($baseDimensions.Mass), $($baseDimensions.Time), $($baseDimensions.ElectricCurrent), $($baseDimensions.Temperature), $($baseDimensions.AmountOfSubstance), $($baseDimensions.LuminousIntensity)); +"@; }@" } -"@; - if ($quantity.Logarithmic -eq $true) { - # Call another script function to generate logarithm-specific arithmetic operator code. - GenerateLogarithmicArithmeticOperators -quantityName $quantityName -baseUnitFieldName $baseUnitFieldName -baseType $baseType -scalingFactor $quantity.LogarithmicScalingFactor - } - elseif ($quantity.GenerateArithmetic -eq $true) {@" - - #region Arithmetic Operators - - public static $quantityName operator -($quantityName right) +"@; # Windows Runtime Component requires a default constructor + if ($wrc) {@" + /// + /// Creates the quantity with a value of 0 in the base unit $baseUnitSingularName. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public $quantityName() { - return new $quantityName(-right.Value, right.Unit); + _value = 0; + _unit = BaseUnit; } +"@; } @" - public static $quantityName operator +($quantityName left, $quantityName right) + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + $privateAccessModifierIfWrc $quantityName($valueType numericValue, $unitEnumName unit) { - return new $quantityName(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + if(unit == $unitEnumName.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + +"@; if ($quantity.BaseType -eq "double") {@" + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); +"@; } else {@" + _value = numericValue; +"@; }@" + _unit = unit; } +"@; + GenerateStaticProperties $genArgs + GenerateProperties $genArgs + GenerateConversionProperties $genArgs + GenerateStaticMethods $genArgs + GenerateStaticFactoryMethods $genArgs + GenerateStaticParseMethods $genArgs + GenerateArithmeticOperators $genArgs + GenerateEqualityAndComparison $genArgs + GenerateConversionMethods $genArgs +@" - public static $quantityName operator -($quantityName left, $quantityName right) + #region ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() { - return new $quantityName(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + return ToString(Unit); } - public static $quantityName operator *($baseType left, $quantityName right) + /// + /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. + public string ToString($unitEnumName unit) { - return new $quantityName(left * right.Value, right.Unit); + return ToString(unit, null, 2); } - public static $quantityName operator *($quantityName left, $baseType right) + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// Unit representation to use. + /// String representation. +"@; # Windows Runtime Component does not support IFormatProvider type + if ($wrc) {@" + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString($unitEnumName unit, [CanBeNull] string cultureName) { - return new $quantityName(left.Value * right, left.Unit); + var provider = cultureName; +"@; } else {@" + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider) + { +"@; }@" + return ToString(unit, provider, 2); } - public static $quantityName operator /($quantityName left, $baseType right) + /// + /// Get string representation of value and unit. + /// + /// Unit representation to use. + /// The number of significant digits after the radix point. + /// String representation. +"@; # Windows Runtime Component does not support IFormatProvider type + if ($wrc) {@" + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString($unitEnumName unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) { - return new $quantityName(left.Value / right, left.Unit); + var provider = cultureName; +"@; } else {@" + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { +"@; }@" + double value = As(unit); + string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(unit, provider, format); } - public static double operator /($quantityName left, $quantityName right) + /// + /// Get string representation of value and unit. + /// + /// Unit representation to use. + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. +"@; # Windows Runtime Component does not support IFormatProvider type + if ($wrc) {@" + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString($unitEnumName unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { - return left.$baseUnitPluralName / right.$baseUnitPluralName; + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + { +"@; }@" + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + double value = As(unit); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } #endregion +"@; if ($wrc) {@" + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } +"@; } else {@" "@; }@" + } +} +"@; +} - public static bool operator <=($quantityName left, $quantityName right) +function GenerateStaticProperties([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $baseUnitSingularName = $genArgs.BaseUnit.SingularName + $valueType = $genArgs.Quantity.BaseType +@" + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of $quantityName, which is $baseUnitSingularName. All conversions go via this value. + /// + public static $unitEnumName BaseUnit => $unitEnumName.$baseUnitSingularName; + + /// + /// Represents the largest possible value of $quantityName + /// + public static $quantityName MaxValue => new $quantityName($valueType.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of $quantityName + /// + public static $quantityName MinValue => new $quantityName($valueType.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.$quantityName; + + /// + /// All units of measurement for the $quantityName quantity. + /// + public static $unitEnumName[] Units { get; } = Enum.GetValues(typeof($unitEnumName)).Cast<$unitEnumName>().Except(new $unitEnumName[]{ $unitEnumName.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit $baseUnitSingularName. + /// + public static $quantityName Zero => new $quantityName(0, BaseUnit); + + #endregion +"@; +} + +function GenerateProperties([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $baseUnitSingularName = $genArgs.BaseUnit.SingularName + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// +"@; # Windows Runtime Component does not support decimal + if ($wrc) {@" + public double Value => Convert.ToDouble(_value); +"@; } else {@" + public $valueType Value => _value; +"@; } +@" + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public $unitEnumName Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => $quantityName.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => $quantityName.BaseDimensions; + + #endregion +"@; +} + +function GenerateConversionProperties([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $units = $genArgs.Quantity.Units +@" + + #region Conversion Properties +"@; + foreach ($unit in $units) { + $propertyName = $unit.PluralName; + $obsoleteAttribute = GetObsoleteAttribute($unit); + if ($obsoleteAttribute) + { + $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page + } +@" + + /// + /// Get $quantityName in $propertyName. + /// $($obsoleteAttribute) + public double $propertyName => As($unitEnumName.$($unit.SingularName)); +"@; } +@" + + #endregion +"@; +} + +function GenerateStaticMethods([GeneratorArgs]$genArgs) +{ + $unitEnumName = $genArgs.UnitEnumName +@" + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation($unitEnumName unit) { - return left.Value <= right.AsBaseNumericType(left.Unit); + return GetAbbreviation(unit, null); } - public static bool operator >=($quantityName left, $quantityName right) + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation($unitEnumName unit, [CanBeNull] string cultureName) { - return left.Value >= right.AsBaseNumericType(left.Unit); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation($unitEnumName unit, [CanBeNull] IFormatProvider provider) + { +"@; }@" + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - public static bool operator <($quantityName left, $quantityName right) + #endregion +"@; +} + +function GenerateStaticFactoryMethods([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $units = $genArgs.Quantity.Units + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Static Factory Methods + +"@; foreach ($unit in $units) { + $valueParamName = $unit.PluralName.ToLowerInvariant(); + $obsoleteAttribute = GetObsoleteAttribute($unit); + if ($obsoleteAttribute) + { + $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page + } + @" + /// + /// Get $quantityName from $($unit.PluralName). + /// $($obsoleteAttribute) + /// If value is NaN or Infinity. +"@; # Windows Runtime Component does not support overloads with same number of parameters + if ($wrc) {@" + [Windows.Foundation.Metadata.DefaultOverload] + public static $quantityName From$($unit.PluralName)(double $valueParamName) +"@; } else {@" + public static $quantityName From$($unit.PluralName)(QuantityValue $valueParamName) +"@; }@" { - return left.Value < right.AsBaseNumericType(left.Unit); + $valueType value = ($valueType) $valueParamName; + return new $quantityName(value, $unitEnumName.$($unit.SingularName)); } +"@; }@" - public static bool operator >($quantityName left, $quantityName right) + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// $quantityName unit value. +"@; # Windows Runtime Component does not support parameters named 'value' +if ($wrc) {@" + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static $quantityName From(double value, $unitEnumName fromUnit) +"@; } else {@" + public static $quantityName From(QuantityValue value, $unitEnumName fromUnit) +"@; }@" { - return left.Value > right.AsBaseNumericType(left.Unit); + return new $quantityName(($valueType)value, fromUnit); } - #region Parsing + #endregion +"@; + +} + +function GenerateStaticParseMethods([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $baseUnitPluralName = $genArgs.BaseUnit.PluralName + $units = $genArgs.Quantity.Units + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #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} - /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -170,109 +519,554 @@ namespace UnitsNet /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static $quantityName Parse(string str, [CanBeNull] IFormatProvider provider) + public static $quantityName Parse(string str) { - return ParseInternal(str, provider); + return ParseInternal(str, null); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out $quantityName result) + /// 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. + /// +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static $quantityName Parse(string str, [CanBeNull] string cultureName) { - return TryParseInternal(str, provider, out result); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. + public static $quantityName Parse(string str, [CanBeNull] IFormatProvider provider) + { +"@; }@" + return ParseInternal(str, provider); } /// - /// Parse a unit string. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Resulting unit quantity if successful. /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static $unitEnumName ParseUnit(string str, IFormatProvider provider = null) + public static bool TryParse([CanBeNull] string str, out $quantityName result) { - return ParseUnitInternal(str, provider); + return TryParseInternal(str, null, out result); } /// - /// Parse a unit string. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// The parsed unit if successful. + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out $quantityName result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out $quantityName result) + { +"@; }@" + return TryParseInternal(str, provider, out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static $unitEnumName ParseUnit(string str) + { + return ParseUnitInternal(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static $unitEnumName ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. + public static $unitEnumName ParseUnit(string str, IFormatProvider provider = null) + { +"@; }@" + return ParseUnitInternal(str, provider); + } + + public static bool TryParseUnit(string str, out $unitEnumName unit) + { + return TryParseUnitInternal(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", new CultureInfo("en-US")); /// +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out $unitEnumName unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider provider, out $unitEnumName unit) { +"@; }@" return TryParseUnitInternal(str, provider, out unit); } - #endregion + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.Parse("5.5 m", new CultureInfo("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. + /// + private static $quantityName ParseInternal(string str, [CanBeNull] IFormatProvider provider) + { + if (str == null) throw new ArgumentNullException(nameof(str)); - #region ToString Methods + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.Parse<$quantityName, $unitEnumName>(str, provider, ParseUnitInternal, From); + } /// - /// Get string representation of value and unit. Using two significant digits after radix. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. - /// String representation. - public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + private static bool TryParseInternal([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out $quantityName result) { - return ToString(unit, provider, 2); + result = default; + + if(string.IsNullOrWhiteSpace(str)) + return false; + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + return QuantityParser.Default.TryParse<$quantityName, $unitEnumName>(str, provider, TryParseUnitInternal, From, out result); } /// - /// Get string representation of value and unit. + /// Parse a unit string. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to if null. - /// The number of significant digits after the radix point. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + private static $unitEnumName ParseUnitInternal(string str, IFormatProvider provider = null) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + if (str == null) throw new ArgumentNullException(nameof(str)); + + var unit = UnitParser.Default.Parse<$unitEnumName>(str.Trim(), provider); + + if (unit == $unitEnumName.Undefined) + { + var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized $unitEnumName."); + newEx.Data["input"] = str; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; + throw newEx; + } + + return unit; } /// - /// Get string representation of value and unit. + /// Parse a unit string. /// - /// Format to use for localization and number formatting. Defaults to if null. - /// Unit representation to use. - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + private static bool TryParseUnitInternal(string str, IFormatProvider provider, out $unitEnumName unit) { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); + unit = $unitEnumName.Undefined; - provider = provider ?? GlobalConfiguration.DefaultCulture; + if(string.IsNullOrWhiteSpace(str)) + return false; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); - return string.Format(provider, format, formatArgs); + if(!UnitParser.Default.TryParse<$unitEnumName>(str.Trim(), provider, out unit)) + return false; + + if(unit == $unitEnumName.Undefined) + return false; + + return true; } #endregion - } +"@; } + +function GenerateLogarithmicArithmeticOperators([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent + $scalingFactor = $genArgs.Quantity.LogarithmicScalingFactor + # Most logarithmic operators need a simple scaling factor of 10. However, certain units such as voltage ratio need to use 20 instead. + $x = 10 * $scalingFactor; + @" + + #region Logarithmic Arithmetic Operators + + public static $quantityName operator -($quantityName right) + { + return new $quantityName(-right.Value, right.Unit); + } + + public static $quantityName operator +($quantityName left, $quantityName right) + { + // Logarithmic addition + // Formula: $x*log10(10^(x/$x) + 10^(y/$x)) + return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); + } + + public static $quantityName operator -($quantityName left, $quantityName right) + { + // Logarithmic subtraction + // Formula: $x*log10(10^(x/$x) - 10^(y/$x)) + return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); + } + + public static $quantityName operator *($valueType left, $quantityName right) + { + // Logarithmic multiplication = addition + return new $quantityName(left + right.Value, right.Unit); + } + + public static $quantityName operator *($quantityName left, double right) + { + // Logarithmic multiplication = addition + return new $quantityName(left.Value + ($valueType)right, left.Unit); + } + + public static $quantityName operator /($quantityName left, double right) + { + // Logarithmic division = subtraction + return new $quantityName(left.Value - ($valueType)right, left.Unit); + } + + public static double operator /($quantityName left, $quantityName right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); + } + + #endregion +"@; +} + +function GenerateArithmeticOperators([GeneratorArgs]$genArgs) +{ + # Windows Runtime Component does not support operator overloads + if ($wrc -or (-not $quantity.GenerateArithmetic)) { return } + + # Logarithmic units required different arithmetic + if ($quantity.Logarithmic) { + GenerateLogarithmicArithmeticOperators $genArgs + return + } + + $quantityName = $genArgs.Quantity.Name + $baseUnitPluralName = $genArgs.BaseUnit.PluralName + $valueType = $genArgs.Quantity.BaseType + @" + + #region Arithmetic Operators + + public static $quantityName operator -($quantityName right) + { + return new $quantityName(-right.Value, right.Unit); + } + + public static $quantityName operator +($quantityName left, $quantityName right) + { + return new $quantityName(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static $quantityName operator -($quantityName left, $quantityName right) + { + return new $quantityName(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static $quantityName operator *($valueType left, $quantityName right) + { + return new $quantityName(left * right.Value, right.Unit); + } + + public static $quantityName operator *($quantityName left, $valueType right) + { + return new $quantityName(left.Value * right, left.Unit); + } + + public static $quantityName operator /($quantityName left, $valueType right) + { + return new $quantityName(left.Value / right, left.Unit); + } + + public static double operator /($quantityName left, $quantityName right) + { + return left.$baseUnitPluralName / right.$baseUnitPluralName; + } + + #endregion +"@; +} + +function GenerateEqualityAndComparison([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Equality / IComparable + +"@; # Windows Runtime Component does not support operator overloads + if (-not $wrc) {@" + public static bool operator <=($quantityName left, $quantityName right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=($quantityName left, $quantityName right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <($quantityName left, $quantityName right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >($quantityName left, $quantityName right) + { + return left.Value > right.AsBaseNumericType(left.Unit); + } + +"@; }@" + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is $quantityName)) throw new ArgumentException("Expected type $quantityName.", nameof(obj)); + + return CompareTo(($quantityName)obj); + } + +"@; # Windows Runtime Component does not support overloads with same number of parameters +$accessModifier = if ($wrc) { "internal" } else { "public" } @" + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + $accessModifier int CompareTo($quantityName other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another $quantityName within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// + /// + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals($quantityName other, double tolerance, ComparisonType comparisonType) + { + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current $quantityName. + public override int GetHashCode() + { + return new { Value, Unit }.GetHashCode(); + } + + #endregion +"@; +} + +function GenerateConversionMethods([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $valueType = $genArgs.Quantity.BaseType +@" + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As($unitEnumName unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this $quantityName to another $quantityName with the unit representation . + /// + /// A $quantityName with the specified unit. + public $quantityName ToUnit($unitEnumName unit) + { + var convertedValue = AsBaseNumericType(unit); + return new $quantityName(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 $valueType AsBaseUnit() + { + switch(Unit) + { +"@; foreach ($unit in $units) { + $func = $unit.FromUnitToBaseFunc.Replace("x", "_value");@" + case $unitEnumName.$($unit.SingularName): return $func; +"@; }@" + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private $valueType AsBaseNumericType($unitEnumName unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { +"@; foreach ($unit in $units) { + $func = $unit.FromBaseToUnitFunc.Replace("x", "baseUnitValue");@" + case $unitEnumName.$($unit.SingularName): return $func; +"@; }@" + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + #endregion "@; } diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 deleted file mode 100644 index b7e7d54fb5..0000000000 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 +++ /dev/null @@ -1,245 +0,0 @@ -function GenerateQuantitySourceCodeWindowsRuntimeComponent($quantity) -{ - $quantityName = $quantity.Name; - $units = $quantity.Units; - $baseType = $quantity.BaseType; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } - $baseUnitSingularName = $baseUnit.SingularName - $baseUnitPluralName = $baseUnit.PluralName - $baseUnitPluralNameLower = $baseUnitPluralName.ToLowerInvariant() - $unitEnumName = "$quantityName" + "Unit" - -@" -//------------------------------------------------------------------------------ -// -// 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 GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Globalization; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// $($quantity.XmlDoc) - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class $quantityName - { - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - /// Creates the quantity with a value of 0 in the base unit $baseUnitSingularName. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public $quantityName() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to if null. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit, [CanBeNull] string cultureName) - { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - /// - /// Length.Parse("5.5 m", new CultureInfo("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 $quantityName Parse(string str, [CanBeNull] string cultureName) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - - return ParseInternal(str, provider); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out $quantityName result) - { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - - return TryParseInternal(str, provider, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static $unitEnumName ParseUnit(string str, [CanBeNull] string cultureName) - { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - - return ParseUnitInternal(str, provider); - } - - /// - /// Try to parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out $unitEnumName unit) - { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - - return TryParseUnitInternal(str, provider, out unit); - } - - #endregion - - #region ToString Methods - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - /// String representation. - public string ToString($unitEnumName unit, [CanBeNull] string cultureName) - { - return ToString(unit, cultureName, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - /// The number of significant digits after the radix point. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) - { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); - } - - /// - /// Get string representation of value and unit. - /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - /// Unit representation to use. - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? GlobalConfiguration.DefaultCulture : new CultureInfo(cultureName); - - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - } -} -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateTemplates.ps1 b/UnitsNet/Scripts/Include-GenerateTemplates.ps1 index 915c6b2ebb..f6b2d15ce7 100644 --- a/UnitsNet/Scripts/Include-GenerateTemplates.ps1 +++ b/UnitsNet/Scripts/Include-GenerateTemplates.ps1 @@ -3,11 +3,11 @@ Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats #> -function GetObsoleteAttribute($quantity) +function GetObsoleteAttribute($quantityOrUnit) { - if ($quantity.ObsoleteText) + if ($quantityOrUnit.ObsoleteText) { - return "[System.Obsolete(""$($quantity.ObsoleteText)"")]"; + return "[System.Obsolete(""$($quantityOrUnit.ObsoleteText)"")]"; } return ""; -} \ No newline at end of file +} diff --git a/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 index d93612a493..6248119c7a 100644 --- a/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 @@ -1,12 +1,14 @@ -function GenerateUnitTestBaseClassSourceCode($quantity) +using module ".\Types.psm1" +function GenerateUnitTestBaseClassSourceCode([Quantity]$quantity) { - $quantityName = $quantity.Name; - $baseType = $quantity.BaseType; - $units = $quantity.Units; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } + $quantityName = $quantity.Name + $units = $quantity.Units + $valueType = $quantity.BaseType + [Unit]$baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } | Select-Object -First 1 + $baseUnitSingularName = $baseUnit.SingularName $baseUnitPluralName = $baseUnit.PluralName - $baseUnitVariableName = $baseUnit.SingularName.ToLowerInvariant(); - $unitEnumName = "$($quantityName)Unit"; + $baseUnitVariableName = $baseUnitSingularName.ToLowerInvariant() + $unitEnumName = "$quantityName" + "Unit" @" //------------------------------------------------------------------------------ @@ -76,7 +78,7 @@ namespace UnitsNet.Tests [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { - Assert.Throws(() => new $quantityName(($baseType)0.0, $unitEnumName.Undefined)); + Assert.Throws(() => new $quantityName(($valueType)0.0, $unitEnumName.Undefined)); } "@; if ($quantity.BaseType -eq "double") {@" diff --git a/UnitsNet/Scripts/Types.psm1 b/UnitsNet/Scripts/Types.psm1 new file mode 100644 index 0000000000..11151b0bd2 --- /dev/null +++ b/UnitsNet/Scripts/Types.psm1 @@ -0,0 +1,43 @@ +class Quantity +{ + [string]$Name + [string]$XmlDocSummary + [string]$XmlDocRemarks + [string]$BaseUnit + [string]$BaseType # TODO Rename me to ValueType + [BaseDimensions]$BaseDimensions = [BaseDimensions]::new() + [boolean]$GenerateArithmetic = $true + [boolean]$Logarithmic = $false + [int]$LogarithmicScalingFactor = 1 + [Unit[]]$Units = @() +} + +class Unit +{ + [string]$SingularName + [string]$PluralName + [string]$XmlDocSummary + [string]$XmlDocRemarks + [string]$FromUnitToBaseFunc + [string]$FromBaseToUnitFunc + [string[]]$Prefixes = @() + [Localization[]]$Localization = @() +} + +class Localization +{ + [string]$Culture + [string[]]$Abbreviations = @() + [string[]]$AbbreviationsWithPrefixes = @() +} + +class BaseDimensions +{ + [int]$Length = 0 + [int]$Mass = 0 + [int]$Time = 0 + [int]$ElectricCurrent = 0 + [int]$Temperature = 0 + [int]$AmountOfSubstance = 0 + [int]$LuminousIntensity = 0 +} diff --git a/generate-code.bat b/generate-code.bat index b005b957fe..27672eeda9 100644 --- a/generate-code.bat +++ b/generate-code.bat @@ -1,3 +1,5 @@ @echo off SET scriptdir=%~dp0 -powershell -ExecutionPolicy Bypass -NoProfile -File "%scriptdir%UnitsNet\Scripts\GenerateUnits.ps1" +pushd "%scriptdir%UnitsNet\Scripts\ +powershell -ExecutionPolicy Bypass -NoProfile -File ".\GenerateUnits.ps1" +popd