diff --git a/.gitattributes b/.gitattributes index 443c437442..72b8ab0ea9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -20,27 +20,9 @@ *.filters text eol=crlf *.vcxitems text eol=crlf - -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -#*.xproj merge=binary -#*.props merge=binary -#*.filters merge=binary -#*.vcxitems merge=binary - # C# -*.cs diff=csharp +*.cs diff=csharp +*.g.cs linguist-generated # Powershell *.ps1 text eol=crlf diff --git a/Build/build-functions.psm1 b/Build/build-functions.psm1 index 6f58691d85..5ff85c1875 100644 --- a/Build/build-functions.psm1 +++ b/Build/build-functions.psm1 @@ -101,7 +101,7 @@ function Start-PackNugets { } write-host -foreground yellow "WindowsRuntimeComponent project not yet supported by dotnet CLI, using nuget.exe instead" - & $nuget pack "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" -Symbols + & $nuget pack "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" write-host -foreground blue "Pack nugets...END`n" } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props index 2854b8b1cb..3c59dfcb57 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props @@ -7,8 +7,6 @@ Units.NET Serialization with Json.NET A helper library for serializing and deserializing types in Units.NET using Json.NET. Copyright (c) 2015 Andreas Gullberg Larsen - true - true true https://github.com/angularsen/UnitsNet https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png @@ -23,11 +21,17 @@ netstandard2.0;net40 UnitsNet.Serialization.JsonNet CS1701;CS1702;CS1705;CS0618 + + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/.gitignore b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/.gitignore deleted file mode 100644 index ccb86a88b8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.g.cs -!Information.WindowsRuntimeComponent.g.cs -!Length.WindowsRuntimeComponent.g.cs -!Level.WindowsRuntimeComponent.g.cs diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..eb339e199a --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs @@ -0,0 +1,774 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Acceleration : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AccelerationUnit? _unit; + + static Acceleration() + { + BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit MeterPerSecondSquared. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Acceleration() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. + /// + public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Acceleration; + + /// + /// All units of measurement for the Acceleration quantity. + /// + public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. + /// + public static Acceleration Zero => new Acceleration(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 AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Acceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Acceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AccelerationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Acceleration from CentimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromCentimetersPerSecondSquared(double centimeterspersecondsquared) + { + double value = (double) centimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); + } + /// + /// Get Acceleration from DecimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromDecimetersPerSecondSquared(double decimeterspersecondsquared) + { + double value = (double) decimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); + } + /// + /// Get Acceleration from FeetPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromFeetPerSecondSquared(double feetpersecondsquared) + { + double value = (double) feetpersecondsquared; + return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); + } + /// + /// Get Acceleration from InchesPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromInchesPerSecondSquared(double inchespersecondsquared) + { + double value = (double) inchespersecondsquared; + return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); + } + /// + /// Get Acceleration from KilometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKilometersPerSecondSquared(double kilometerspersecondsquared) + { + double value = (double) kilometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); + } + /// + /// Get Acceleration from KnotsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKnotsPerHour(double knotsperhour) + { + double value = (double) knotsperhour; + return new Acceleration(value, AccelerationUnit.KnotPerHour); + } + /// + /// Get Acceleration from KnotsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKnotsPerMinute(double knotsperminute) + { + double value = (double) knotsperminute; + return new Acceleration(value, AccelerationUnit.KnotPerMinute); + } + /// + /// Get Acceleration from KnotsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKnotsPerSecond(double knotspersecond) + { + double value = (double) knotspersecond; + return new Acceleration(value, AccelerationUnit.KnotPerSecond); + } + /// + /// Get Acceleration from MetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromMetersPerSecondSquared(double meterspersecondsquared) + { + double value = (double) meterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); + } + /// + /// Get Acceleration from MicrometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromMicrometersPerSecondSquared(double micrometerspersecondsquared) + { + double value = (double) micrometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); + } + /// + /// Get Acceleration from MillimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromMillimetersPerSecondSquared(double millimeterspersecondsquared) + { + double value = (double) millimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); + } + /// + /// Get Acceleration from NanometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromNanometersPerSecondSquared(double nanometerspersecondsquared) + { + double value = (double) nanometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); + } + /// + /// Get Acceleration from StandardGravity. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromStandardGravity(double standardgravity) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Acceleration From(double value, AccelerationUnit fromUnit) + { + return new Acceleration((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Acceleration Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Acceleration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Acceleration result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AccelerationUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..ce290025ca --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,791 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 AmountOfSubstance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AmountOfSubstanceUnit? _unit; + + static AmountOfSubstance() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Mole. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public AmountOfSubstance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. + /// + public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AmountOfSubstance; + + /// + /// All units of measurement for the AmountOfSubstance quantity. + /// + public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Mole. + /// + public static AmountOfSubstance Zero => new AmountOfSubstance(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 AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmountOfSubstance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AmountOfSubstanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AmountOfSubstance from Centimoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromCentimoles(double centimoles) + { + double value = (double) centimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); + } + /// + /// Get AmountOfSubstance from CentipoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromCentipoundMoles(double centipoundmoles) + { + double value = (double) centipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); + } + /// + /// Get AmountOfSubstance from Decimoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromDecimoles(double decimoles) + { + double value = (double) decimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); + } + /// + /// Get AmountOfSubstance from DecipoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromDecipoundMoles(double decipoundmoles) + { + double value = (double) decipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); + } + /// + /// Get AmountOfSubstance from Kilomoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromKilomoles(double kilomoles) + { + double value = (double) kilomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); + } + /// + /// Get AmountOfSubstance from KilopoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromKilopoundMoles(double kilopoundmoles) + { + double value = (double) kilopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); + } + /// + /// Get AmountOfSubstance from Micromoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMicromoles(double micromoles) + { + double value = (double) micromoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); + } + /// + /// Get AmountOfSubstance from MicropoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMicropoundMoles(double micropoundmoles) + { + double value = (double) micropoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); + } + /// + /// Get AmountOfSubstance from Millimoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMillimoles(double millimoles) + { + double value = (double) millimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); + } + /// + /// Get AmountOfSubstance from MillipoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMillipoundMoles(double millipoundmoles) + { + double value = (double) millipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); + } + /// + /// Get AmountOfSubstance from Moles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMoles(double moles) + { + double value = (double) moles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); + } + /// + /// Get AmountOfSubstance from Nanomoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromNanomoles(double nanomoles) + { + double value = (double) nanomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); + } + /// + /// Get AmountOfSubstance from NanopoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromNanopoundMoles(double nanopoundmoles) + { + double value = (double) nanopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); + } + /// + /// Get AmountOfSubstance from PoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromPoundMoles(double poundmoles) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUnit) + { + return new AmountOfSubstance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AmountOfSubstance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AmountOfSubstance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AmountOfSubstanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..ce45c7407c --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs @@ -0,0 +1,621 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. + /// + // 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 AmplitudeRatio : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AmplitudeRatioUnit? _unit; + + static AmplitudeRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit DecibelVolt. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public AmplitudeRatio() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. + /// + public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AmplitudeRatio; + + /// + /// All units of measurement for the AmplitudeRatio quantity. + /// + public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. + /// + public static AmplitudeRatio Zero => new AmplitudeRatio(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 AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmplitudeRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AmplitudeRatioUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AmplitudeRatio from DecibelMicrovolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelMicrovolts(double decibelmicrovolts) + { + double value = (double) decibelmicrovolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); + } + /// + /// Get AmplitudeRatio from DecibelMillivolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelMillivolts(double decibelmillivolts) + { + double value = (double) decibelmillivolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); + } + /// + /// Get AmplitudeRatio from DecibelsUnloaded. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelsUnloaded(double decibelsunloaded) + { + double value = (double) decibelsunloaded; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); + } + /// + /// Get AmplitudeRatio from DecibelVolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelVolts(double decibelvolts) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) + { + return new AmplitudeRatio((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AmplitudeRatio Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AmplitudeRatio result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AmplitudeRatioUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..d721fd78bb --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs @@ -0,0 +1,791 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Angle : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AngleUnit? _unit; + + static Angle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit Degree. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Angle() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Angle, which is Degree. All conversions go via this value. + /// + public static AngleUnit BaseUnit => AngleUnit.Degree; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Angle; + + /// + /// All units of measurement for the Angle quantity. + /// + public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Degree. + /// + public static Angle Zero => new Angle(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 AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Angle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Angle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AngleUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AngleUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Angle from Arcminutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromArcminutes(double arcminutes) + { + double value = (double) arcminutes; + return new Angle(value, AngleUnit.Arcminute); + } + /// + /// Get Angle from Arcseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromArcseconds(double arcseconds) + { + double value = (double) arcseconds; + return new Angle(value, AngleUnit.Arcsecond); + } + /// + /// Get Angle from Centiradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromCentiradians(double centiradians) + { + double value = (double) centiradians; + return new Angle(value, AngleUnit.Centiradian); + } + /// + /// Get Angle from Deciradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromDeciradians(double deciradians) + { + double value = (double) deciradians; + return new Angle(value, AngleUnit.Deciradian); + } + /// + /// Get Angle from Degrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromDegrees(double degrees) + { + double value = (double) degrees; + return new Angle(value, AngleUnit.Degree); + } + /// + /// Get Angle from Gradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromGradians(double gradians) + { + double value = (double) gradians; + return new Angle(value, AngleUnit.Gradian); + } + /// + /// Get Angle from Microdegrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMicrodegrees(double microdegrees) + { + double value = (double) microdegrees; + return new Angle(value, AngleUnit.Microdegree); + } + /// + /// Get Angle from Microradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMicroradians(double microradians) + { + double value = (double) microradians; + return new Angle(value, AngleUnit.Microradian); + } + /// + /// Get Angle from Millidegrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMillidegrees(double millidegrees) + { + double value = (double) millidegrees; + return new Angle(value, AngleUnit.Millidegree); + } + /// + /// Get Angle from Milliradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMilliradians(double milliradians) + { + double value = (double) milliradians; + return new Angle(value, AngleUnit.Milliradian); + } + /// + /// Get Angle from Nanodegrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromNanodegrees(double nanodegrees) + { + double value = (double) nanodegrees; + return new Angle(value, AngleUnit.Nanodegree); + } + /// + /// Get Angle from Nanoradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromNanoradians(double nanoradians) + { + double value = (double) nanoradians; + return new Angle(value, AngleUnit.Nanoradian); + } + /// + /// Get Angle from Radians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromRadians(double radians) + { + double value = (double) radians; + return new Angle(value, AngleUnit.Radian); + } + /// + /// Get Angle from Revolutions. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromRevolutions(double revolutions) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Angle From(double value, AngleUnit fromUnit) + { + return new Angle((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Angle Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Angle result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Angle result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AngleUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..6af6c3626d --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ApparentEnergy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentEnergyUnit? _unit; + + static ApparentEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit VoltampereHour. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ApparentEnergy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. + /// + public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ApparentEnergy; + + /// + /// All units of measurement for the ApparentEnergy quantity. + /// + public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. + /// + public static ApparentEnergy Zero => new ApparentEnergy(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 ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ApparentEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ApparentEnergy from KilovoltampereHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentEnergy FromKilovoltampereHours(double kilovoltamperehours) + { + double value = (double) kilovoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); + } + /// + /// Get ApparentEnergy from MegavoltampereHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentEnergy FromMegavoltampereHours(double megavoltamperehours) + { + double value = (double) megavoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); + } + /// + /// Get ApparentEnergy from VoltampereHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentEnergy FromVoltampereHours(double voltamperehours) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) + { + return new ApparentEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ApparentEnergy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ApparentEnergy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ApparentEnergyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..3f17f61de0 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs @@ -0,0 +1,621 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ApparentPower : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentPowerUnit? _unit; + + static ApparentPower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Voltampere. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ApparentPower() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. + /// + public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ApparentPower; + + /// + /// All units of measurement for the ApparentPower quantity. + /// + public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. + /// + public static ApparentPower Zero => new ApparentPower(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 ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentPower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentPower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ApparentPowerUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ApparentPower from Gigavoltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromGigavoltamperes(double gigavoltamperes) + { + double value = (double) gigavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); + } + /// + /// Get ApparentPower from Kilovoltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromKilovoltamperes(double kilovoltamperes) + { + double value = (double) kilovoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); + } + /// + /// Get ApparentPower from Megavoltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromMegavoltamperes(double megavoltamperes) + { + double value = (double) megavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); + } + /// + /// Get ApparentPower from Voltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromVoltamperes(double voltamperes) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ApparentPower From(double value, ApparentPowerUnit fromUnit) + { + return new ApparentPower((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ApparentPower Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ApparentPower result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ApparentPower result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ApparentPowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ApparentPowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ApparentPowerUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..7ea98e2ea6 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs @@ -0,0 +1,774 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 Area : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaUnit? _unit; + + static Area() + { + BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit SquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Area() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Area, which is SquareMeter. All conversions go via this value. + /// + public static AreaUnit BaseUnit => AreaUnit.SquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Area; + + /// + /// All units of measurement for the Area quantity. + /// + public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. + /// + public static Area Zero => new Area(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 AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Area.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Area.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AreaUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Area from Acres. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromAcres(double acres) + { + double value = (double) acres; + return new Area(value, AreaUnit.Acre); + } + /// + /// Get Area from Hectares. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromHectares(double hectares) + { + double value = (double) hectares; + return new Area(value, AreaUnit.Hectare); + } + /// + /// Get Area from SquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareCentimeters(double squarecentimeters) + { + double value = (double) squarecentimeters; + return new Area(value, AreaUnit.SquareCentimeter); + } + /// + /// Get Area from SquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareDecimeters(double squaredecimeters) + { + double value = (double) squaredecimeters; + return new Area(value, AreaUnit.SquareDecimeter); + } + /// + /// Get Area from SquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareFeet(double squarefeet) + { + double value = (double) squarefeet; + return new Area(value, AreaUnit.SquareFoot); + } + /// + /// Get Area from SquareInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareInches(double squareinches) + { + double value = (double) squareinches; + return new Area(value, AreaUnit.SquareInch); + } + /// + /// Get Area from SquareKilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareKilometers(double squarekilometers) + { + double value = (double) squarekilometers; + return new Area(value, AreaUnit.SquareKilometer); + } + /// + /// Get Area from SquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMeters(double squaremeters) + { + double value = (double) squaremeters; + return new Area(value, AreaUnit.SquareMeter); + } + /// + /// Get Area from SquareMicrometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMicrometers(double squaremicrometers) + { + double value = (double) squaremicrometers; + return new Area(value, AreaUnit.SquareMicrometer); + } + /// + /// Get Area from SquareMiles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMiles(double squaremiles) + { + double value = (double) squaremiles; + return new Area(value, AreaUnit.SquareMile); + } + /// + /// Get Area from SquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMillimeters(double squaremillimeters) + { + double value = (double) squaremillimeters; + return new Area(value, AreaUnit.SquareMillimeter); + } + /// + /// Get Area from SquareYards. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareYards(double squareyards) + { + double value = (double) squareyards; + return new Area(value, AreaUnit.SquareYard); + } + /// + /// Get Area from UsSurveySquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromUsSurveySquareFeet(double ussurveysquarefeet) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Area From(double value, AreaUnit fromUnit) + { + return new Area((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Area Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Area result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Area result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AreaUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..f13fa07cad --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,570 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The area density of a two-dimensional object is calculated as the mass per unit area. + /// + // 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 AreaDensity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaDensityUnit? _unit; + + static AreaDensity() + { + BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramPerSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public AreaDensity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. + /// + public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AreaDensity; + + /// + /// All units of measurement for the AreaDensity quantity. + /// + public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. + /// + public static AreaDensity Zero => new AreaDensity(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 AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AreaDensity in KilogramsPerSquareMeter. + /// + public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AreaDensity from KilogramsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaDensity FromKilogramsPerSquareMeter(double kilogramspersquaremeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static AreaDensity From(double value, AreaDensityUnit fromUnit) + { + return new AreaDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AreaDensity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AreaDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AreaDensity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AreaDensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..40ba8402c8 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs @@ -0,0 +1,655 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// A geometric property of an area that reflects how its points are distributed with regard to an axis. + /// + // 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 AreaMomentOfInertia : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaMomentOfInertiaUnit? _unit; + + static AreaMomentOfInertia() + { + BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit MeterToTheFourth. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public AreaMomentOfInertia() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. + /// + public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AreaMomentOfInertia; + + /// + /// All units of measurement for the AreaMomentOfInertia quantity. + /// + public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. + /// + public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(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 AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AreaMomentOfInertia from CentimetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromCentimetersToTheFourth(double centimeterstothefourth) + { + double value = (double) centimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from DecimetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromDecimetersToTheFourth(double decimeterstothefourth) + { + double value = (double) decimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from FeetToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromFeetToTheFourth(double feettothefourth) + { + double value = (double) feettothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); + } + /// + /// Get AreaMomentOfInertia from InchesToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromInchesToTheFourth(double inchestothefourth) + { + double value = (double) inchestothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromMetersToTheFourth(double meterstothefourth) + { + double value = (double) meterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MillimetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromMillimetersToTheFourth(double millimeterstothefourth) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fromUnit) + { + return new AreaMomentOfInertia((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AreaMomentOfInertia Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AreaMomentOfInertia result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AreaMomentOfInertiaUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..550439140c --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs @@ -0,0 +1,998 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Bit_rate + /// + // 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 BitRate : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BitRateUnit? _unit; + + static BitRate() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit BitPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public BitRate() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. + /// + public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.BitRate; + + /// + /// All units of measurement for the BitRate quantity. + /// + public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. + /// + public static BitRate Zero => new BitRate(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 BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BitRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BitRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BitRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get BitRate from BitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromBitsPerSecond(double bitspersecond) + { + decimal value = (decimal) bitspersecond; + return new BitRate(value, BitRateUnit.BitPerSecond); + } + /// + /// Get BitRate from BytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromBytesPerSecond(double bytespersecond) + { + decimal value = (decimal) bytespersecond; + return new BitRate(value, BitRateUnit.BytePerSecond); + } + /// + /// Get BitRate from ExabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExabitsPerSecond(double exabitspersecond) + { + decimal value = (decimal) exabitspersecond; + return new BitRate(value, BitRateUnit.ExabitPerSecond); + } + /// + /// Get BitRate from ExabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExabytesPerSecond(double exabytespersecond) + { + decimal value = (decimal) exabytespersecond; + return new BitRate(value, BitRateUnit.ExabytePerSecond); + } + /// + /// Get BitRate from ExbibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExbibitsPerSecond(double exbibitspersecond) + { + decimal value = (decimal) exbibitspersecond; + return new BitRate(value, BitRateUnit.ExbibitPerSecond); + } + /// + /// Get BitRate from ExbibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExbibytesPerSecond(double exbibytespersecond) + { + decimal value = (decimal) exbibytespersecond; + return new BitRate(value, BitRateUnit.ExbibytePerSecond); + } + /// + /// Get BitRate from GibibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGibibitsPerSecond(double gibibitspersecond) + { + decimal value = (decimal) gibibitspersecond; + return new BitRate(value, BitRateUnit.GibibitPerSecond); + } + /// + /// Get BitRate from GibibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGibibytesPerSecond(double gibibytespersecond) + { + decimal value = (decimal) gibibytespersecond; + return new BitRate(value, BitRateUnit.GibibytePerSecond); + } + /// + /// Get BitRate from GigabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGigabitsPerSecond(double gigabitspersecond) + { + decimal value = (decimal) gigabitspersecond; + return new BitRate(value, BitRateUnit.GigabitPerSecond); + } + /// + /// Get BitRate from GigabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGigabytesPerSecond(double gigabytespersecond) + { + decimal value = (decimal) gigabytespersecond; + return new BitRate(value, BitRateUnit.GigabytePerSecond); + } + /// + /// Get BitRate from KibibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKibibitsPerSecond(double kibibitspersecond) + { + decimal value = (decimal) kibibitspersecond; + return new BitRate(value, BitRateUnit.KibibitPerSecond); + } + /// + /// Get BitRate from KibibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKibibytesPerSecond(double kibibytespersecond) + { + decimal value = (decimal) kibibytespersecond; + return new BitRate(value, BitRateUnit.KibibytePerSecond); + } + /// + /// Get BitRate from KilobitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKilobitsPerSecond(double kilobitspersecond) + { + decimal value = (decimal) kilobitspersecond; + return new BitRate(value, BitRateUnit.KilobitPerSecond); + } + /// + /// Get BitRate from KilobytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKilobytesPerSecond(double kilobytespersecond) + { + decimal value = (decimal) kilobytespersecond; + return new BitRate(value, BitRateUnit.KilobytePerSecond); + } + /// + /// Get BitRate from MebibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMebibitsPerSecond(double mebibitspersecond) + { + decimal value = (decimal) mebibitspersecond; + return new BitRate(value, BitRateUnit.MebibitPerSecond); + } + /// + /// Get BitRate from MebibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMebibytesPerSecond(double mebibytespersecond) + { + decimal value = (decimal) mebibytespersecond; + return new BitRate(value, BitRateUnit.MebibytePerSecond); + } + /// + /// Get BitRate from MegabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMegabitsPerSecond(double megabitspersecond) + { + decimal value = (decimal) megabitspersecond; + return new BitRate(value, BitRateUnit.MegabitPerSecond); + } + /// + /// Get BitRate from MegabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMegabytesPerSecond(double megabytespersecond) + { + decimal value = (decimal) megabytespersecond; + return new BitRate(value, BitRateUnit.MegabytePerSecond); + } + /// + /// Get BitRate from PebibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPebibitsPerSecond(double pebibitspersecond) + { + decimal value = (decimal) pebibitspersecond; + return new BitRate(value, BitRateUnit.PebibitPerSecond); + } + /// + /// Get BitRate from PebibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPebibytesPerSecond(double pebibytespersecond) + { + decimal value = (decimal) pebibytespersecond; + return new BitRate(value, BitRateUnit.PebibytePerSecond); + } + /// + /// Get BitRate from PetabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPetabitsPerSecond(double petabitspersecond) + { + decimal value = (decimal) petabitspersecond; + return new BitRate(value, BitRateUnit.PetabitPerSecond); + } + /// + /// Get BitRate from PetabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPetabytesPerSecond(double petabytespersecond) + { + decimal value = (decimal) petabytespersecond; + return new BitRate(value, BitRateUnit.PetabytePerSecond); + } + /// + /// Get BitRate from TebibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTebibitsPerSecond(double tebibitspersecond) + { + decimal value = (decimal) tebibitspersecond; + return new BitRate(value, BitRateUnit.TebibitPerSecond); + } + /// + /// Get BitRate from TebibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTebibytesPerSecond(double tebibytespersecond) + { + decimal value = (decimal) tebibytespersecond; + return new BitRate(value, BitRateUnit.TebibytePerSecond); + } + /// + /// Get BitRate from TerabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTerabitsPerSecond(double terabitspersecond) + { + decimal value = (decimal) terabitspersecond; + return new BitRate(value, BitRateUnit.TerabitPerSecond); + } + /// + /// Get BitRate from TerabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTerabytesPerSecond(double terabytespersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static BitRate From(double value, BitRateUnit fromUnit) + { + return new BitRate((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 BitRate Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 BitRate Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out BitRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 BitRate result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out BitRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 BitRateUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..63ab43d231 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 BrakeSpecificFuelConsumption : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BrakeSpecificFuelConsumptionUnit? _unit; + + static BrakeSpecificFuelConsumption() + { + BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramPerJoule. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public BrakeSpecificFuelConsumption() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. + /// + public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; + + /// + /// 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 static QuantityType QuantityType => QuantityType.BrakeSpecificFuelConsumption; + + /// + /// All units of measurement for the BrakeSpecificFuelConsumption quantity. + /// + public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. + /// + public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(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 BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double gramsperkilowatthour) + { + double value = (double) gramsperkilowatthour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + } + /// + /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double kilogramsperjoule) + { + double value = (double) kilogramsperjoule; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + } + /// + /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double poundspermechanicalhorsepowerhour) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelConsumptionUnit fromUnit) + { + return new BrakeSpecificFuelConsumption((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsumption result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 BrakeSpecificFuelConsumption result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 BrakeSpecificFuelConsumptionUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..e420af6a62 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Capacitance is the ability of a body to store an electric charge. + /// + /// + /// https://en.wikipedia.org/wiki/Capacitance + /// + // 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 Capacitance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CapacitanceUnit? _unit; + + static Capacitance() + { + BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Farad. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Capacitance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Capacitance, which is Farad. All conversions go via this value. + /// + public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Capacitance; + + /// + /// All units of measurement for the Capacitance quantity. + /// + public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Farad. + /// + public static Capacitance Zero => new Capacitance(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 CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Capacitance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Capacitance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Capacitance in Farads. + /// + public double Farads => As(CapacitanceUnit.Farad); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CapacitanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Capacitance from Farads. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Capacitance FromFarads(double farads) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Capacitance From(double value, CapacitanceUnit fromUnit) + { + return new Capacitance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Capacitance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Capacitance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Capacitance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out CapacitanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 CapacitanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..1173f6f511 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// A unit that represents a fractional change in size in response to a change in temperature. + /// + // 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 CoefficientOfThermalExpansion : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CoefficientOfThermalExpansionUnit? _unit; + + static CoefficientOfThermalExpansion() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit InverseKelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public CoefficientOfThermalExpansion() + { + _value = 0; + _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 CoefficientOfThermalExpansion(double numericValue, CoefficientOfThermalExpansionUnit unit) + { + if(unit == CoefficientOfThermalExpansionUnit.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 CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value. + /// + public static CoefficientOfThermalExpansionUnit BaseUnit => CoefficientOfThermalExpansionUnit.InverseKelvin; + + /// + /// Represents the largest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MaxValue => new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MinValue => new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.CoefficientOfThermalExpansion; + + /// + /// All units of measurement for the CoefficientOfThermalExpansion quantity. + /// + public static CoefficientOfThermalExpansionUnit[] Units { get; } = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. + /// + public static CoefficientOfThermalExpansion Zero => new CoefficientOfThermalExpansion(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 CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => CoefficientOfThermalExpansion.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeCelsius. + /// + public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeFahrenheit. + /// + public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + + /// + /// Get CoefficientOfThermalExpansion in InverseKelvin. + /// + public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(double inversedegreecelsius) + { + double value = (double) inversedegreecelsius; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + } + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(double inversedegreefahrenheit) + { + double value = (double) inversedegreefahrenheit; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + } + /// + /// Get CoefficientOfThermalExpansion from InverseKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static CoefficientOfThermalExpansion FromInverseKelvin(double inversekelvin) + { + double value = (double) inversekelvin; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// CoefficientOfThermalExpansion unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static CoefficientOfThermalExpansion From(double value, CoefficientOfThermalExpansionUnit fromUnit) + { + return new CoefficientOfThermalExpansion((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} + /// + /// 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 CoefficientOfThermalExpansion Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 CoefficientOfThermalExpansion Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out CoefficientOfThermalExpansion result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 CoefficientOfThermalExpansion result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 CoefficientOfThermalExpansionUnit ParseUnit(string str) + { + return ParseUnit(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 CoefficientOfThermalExpansionUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 CoefficientOfThermalExpansionUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Equality / IComparable + + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is CoefficientOfThermalExpansion)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj)); + + return CompareTo((CoefficientOfThermalExpansion)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(CoefficientOfThermalExpansion other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another CoefficientOfThermalExpansion 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(CoefficientOfThermalExpansion 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 CoefficientOfThermalExpansion. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . + /// + /// A CoefficientOfThermalExpansion with the specified unit. + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new CoefficientOfThermalExpansion(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 CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value*5/9; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue*9/5; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return 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(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..ccd0e18225 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs @@ -0,0 +1,1202 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. + /// + /// + /// http://en.wikipedia.org/wiki/Density + /// + // 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 Density : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DensityUnit? _unit; + + static Density() + { + BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Density() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. + /// + public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Density; + + /// + /// All units of measurement for the Density quantity. + /// + public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// + public static Density Zero => new Density(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 DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Density.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Density.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(DensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Density from CentigramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromCentigramsPerDeciLiter(double centigramsperdeciliter) + { + double value = (double) centigramsperdeciliter; + return new Density(value, DensityUnit.CentigramPerDeciliter); + } + /// + /// Get Density from CentigramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromCentigramsPerLiter(double centigramsperliter) + { + double value = (double) centigramsperliter; + return new Density(value, DensityUnit.CentigramPerLiter); + } + /// + /// Get Density from CentigramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromCentigramsPerMilliliter(double centigramspermilliliter) + { + double value = (double) centigramspermilliliter; + return new Density(value, DensityUnit.CentigramPerMilliliter); + } + /// + /// Get Density from DecigramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromDecigramsPerDeciLiter(double decigramsperdeciliter) + { + double value = (double) decigramsperdeciliter; + return new Density(value, DensityUnit.DecigramPerDeciliter); + } + /// + /// Get Density from DecigramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromDecigramsPerLiter(double decigramsperliter) + { + double value = (double) decigramsperliter; + return new Density(value, DensityUnit.DecigramPerLiter); + } + /// + /// Get Density from DecigramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromDecigramsPerMilliliter(double decigramspermilliliter) + { + double value = (double) decigramspermilliliter; + return new Density(value, DensityUnit.DecigramPerMilliliter); + } + /// + /// Get Density from GramsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerCubicCentimeter(double gramspercubiccentimeter) + { + double value = (double) gramspercubiccentimeter; + return new Density(value, DensityUnit.GramPerCubicCentimeter); + } + /// + /// Get Density from GramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerCubicMeter(double gramspercubicmeter) + { + double value = (double) gramspercubicmeter; + return new Density(value, DensityUnit.GramPerCubicMeter); + } + /// + /// Get Density from GramsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerCubicMillimeter(double gramspercubicmillimeter) + { + double value = (double) gramspercubicmillimeter; + return new Density(value, DensityUnit.GramPerCubicMillimeter); + } + /// + /// Get Density from GramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerDeciLiter(double gramsperdeciliter) + { + double value = (double) gramsperdeciliter; + return new Density(value, DensityUnit.GramPerDeciliter); + } + /// + /// Get Density from GramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerLiter(double gramsperliter) + { + double value = (double) gramsperliter; + return new Density(value, DensityUnit.GramPerLiter); + } + /// + /// Get Density from GramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerMilliliter(double gramspermilliliter) + { + double value = (double) gramspermilliliter; + return new Density(value, DensityUnit.GramPerMilliliter); + } + /// + /// Get Density from KilogramsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) + { + double value = (double) kilogramspercubiccentimeter; + return new Density(value, DensityUnit.KilogramPerCubicCentimeter); + } + /// + /// Get Density from KilogramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilogramsPerCubicMeter(double kilogramspercubicmeter) + { + double value = (double) kilogramspercubicmeter; + return new Density(value, DensityUnit.KilogramPerCubicMeter); + } + /// + /// Get Density from KilogramsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) + { + double value = (double) kilogramspercubicmillimeter; + return new Density(value, DensityUnit.KilogramPerCubicMillimeter); + } + /// + /// Get Density from KilopoundsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) + { + double value = (double) kilopoundspercubicfoot; + return new Density(value, DensityUnit.KilopoundPerCubicFoot); + } + /// + /// Get Density from KilopoundsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilopoundsPerCubicInch(double kilopoundspercubicinch) + { + double value = (double) kilopoundspercubicinch; + return new Density(value, DensityUnit.KilopoundPerCubicInch); + } + /// + /// Get Density from MicrogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMicrogramsPerDeciLiter(double microgramsperdeciliter) + { + double value = (double) microgramsperdeciliter; + return new Density(value, DensityUnit.MicrogramPerDeciliter); + } + /// + /// Get Density from MicrogramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMicrogramsPerLiter(double microgramsperliter) + { + double value = (double) microgramsperliter; + return new Density(value, DensityUnit.MicrogramPerLiter); + } + /// + /// Get Density from MicrogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMicrogramsPerMilliliter(double microgramspermilliliter) + { + double value = (double) microgramspermilliliter; + return new Density(value, DensityUnit.MicrogramPerMilliliter); + } + /// + /// Get Density from MilligramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerCubicMeter(double milligramspercubicmeter) + { + double value = (double) milligramspercubicmeter; + return new Density(value, DensityUnit.MilligramPerCubicMeter); + } + /// + /// Get Density from MilligramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerDeciLiter(double milligramsperdeciliter) + { + double value = (double) milligramsperdeciliter; + return new Density(value, DensityUnit.MilligramPerDeciliter); + } + /// + /// Get Density from MilligramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerLiter(double milligramsperliter) + { + double value = (double) milligramsperliter; + return new Density(value, DensityUnit.MilligramPerLiter); + } + /// + /// Get Density from MilligramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerMilliliter(double milligramspermilliliter) + { + double value = (double) milligramspermilliliter; + return new Density(value, DensityUnit.MilligramPerMilliliter); + } + /// + /// Get Density from NanogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromNanogramsPerDeciLiter(double nanogramsperdeciliter) + { + double value = (double) nanogramsperdeciliter; + return new Density(value, DensityUnit.NanogramPerDeciliter); + } + /// + /// Get Density from NanogramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromNanogramsPerLiter(double nanogramsperliter) + { + double value = (double) nanogramsperliter; + return new Density(value, DensityUnit.NanogramPerLiter); + } + /// + /// Get Density from NanogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromNanogramsPerMilliliter(double nanogramspermilliliter) + { + double value = (double) nanogramspermilliliter; + return new Density(value, DensityUnit.NanogramPerMilliliter); + } + /// + /// Get Density from PicogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPicogramsPerDeciLiter(double picogramsperdeciliter) + { + double value = (double) picogramsperdeciliter; + return new Density(value, DensityUnit.PicogramPerDeciliter); + } + /// + /// Get Density from PicogramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPicogramsPerLiter(double picogramsperliter) + { + double value = (double) picogramsperliter; + return new Density(value, DensityUnit.PicogramPerLiter); + } + /// + /// Get Density from PicogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPicogramsPerMilliliter(double picogramspermilliliter) + { + double value = (double) picogramspermilliliter; + return new Density(value, DensityUnit.PicogramPerMilliliter); + } + /// + /// Get Density from PoundsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerCubicFoot(double poundspercubicfoot) + { + double value = (double) poundspercubicfoot; + return new Density(value, DensityUnit.PoundPerCubicFoot); + } + /// + /// Get Density from PoundsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerCubicInch(double poundspercubicinch) + { + double value = (double) poundspercubicinch; + return new Density(value, DensityUnit.PoundPerCubicInch); + } + /// + /// Get Density from PoundsPerImperialGallon. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerImperialGallon(double poundsperimperialgallon) + { + double value = (double) poundsperimperialgallon; + return new Density(value, DensityUnit.PoundPerImperialGallon); + } + /// + /// Get Density from PoundsPerUSGallon. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerUSGallon(double poundsperusgallon) + { + double value = (double) poundsperusgallon; + return new Density(value, DensityUnit.PoundPerUSGallon); + } + /// + /// Get Density from SlugsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromSlugsPerCubicFoot(double slugspercubicfoot) + { + double value = (double) slugspercubicfoot; + return new Density(value, DensityUnit.SlugPerCubicFoot); + } + /// + /// Get Density from TonnesPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) + { + double value = (double) tonnespercubiccentimeter; + return new Density(value, DensityUnit.TonnePerCubicCentimeter); + } + /// + /// Get Density from TonnesPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromTonnesPerCubicMeter(double tonnespercubicmeter) + { + double value = (double) tonnespercubicmeter; + return new Density(value, DensityUnit.TonnePerCubicMeter); + } + /// + /// Get Density from TonnesPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Density From(double value, DensityUnit fromUnit) + { + return new Density((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Density Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Density result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Density result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 DensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..d6da3f36c3 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs @@ -0,0 +1,723 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Duration : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DurationUnit? _unit; + + static Duration() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Second. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Duration() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Duration, which is Second. All conversions go via this value. + /// + public static DurationUnit BaseUnit => DurationUnit.Second; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Duration; + + /// + /// All units of measurement for the Duration quantity. + /// + public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// + public static Duration Zero => new Duration(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 DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Duration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Duration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DurationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(DurationUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Duration from Days. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromDays(double days) + { + double value = (double) days; + return new Duration(value, DurationUnit.Day); + } + /// + /// Get Duration from Hours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromHours(double hours) + { + double value = (double) hours; + return new Duration(value, DurationUnit.Hour); + } + /// + /// Get Duration from Microseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMicroseconds(double microseconds) + { + double value = (double) microseconds; + return new Duration(value, DurationUnit.Microsecond); + } + /// + /// Get Duration from Milliseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMilliseconds(double milliseconds) + { + double value = (double) milliseconds; + return new Duration(value, DurationUnit.Millisecond); + } + /// + /// Get Duration from Minutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMinutes(double minutes) + { + double value = (double) minutes; + return new Duration(value, DurationUnit.Minute); + } + /// + /// Get Duration from Months30. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMonths30(double months30) + { + double value = (double) months30; + return new Duration(value, DurationUnit.Month30); + } + /// + /// Get Duration from Nanoseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromNanoseconds(double nanoseconds) + { + double value = (double) nanoseconds; + return new Duration(value, DurationUnit.Nanosecond); + } + /// + /// Get Duration from Seconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromSeconds(double seconds) + { + double value = (double) seconds; + return new Duration(value, DurationUnit.Second); + } + /// + /// Get Duration from Weeks. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromWeeks(double weeks) + { + double value = (double) weeks; + return new Duration(value, DurationUnit.Week); + } + /// + /// Get Duration from Years365. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromYears365(double years365) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Duration From(double value, DurationUnit fromUnit) + { + return new Duration((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Duration Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Duration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Duration result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DurationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 DurationUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..4faa9c6a73 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,658 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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 + /// + /// + /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity + /// + // 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 DynamicViscosity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DynamicViscosityUnit? _unit; + + static DynamicViscosity() + { + BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public DynamicViscosity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. + /// + public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; + + /// + /// 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 static QuantityType QuantityType => QuantityType.DynamicViscosity; + + /// + /// All units of measurement for the DynamicViscosity quantity. + /// + public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. + /// + public static DynamicViscosity Zero => new DynamicViscosity(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 DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => DynamicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DynamicViscosityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get DynamicViscosity from Centipoise. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromCentipoise(double centipoise) + { + double value = (double) centipoise; + return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); + } + /// + /// Get DynamicViscosity from MicropascalSeconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromMicropascalSeconds(double micropascalseconds) + { + double value = (double) micropascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); + } + /// + /// Get DynamicViscosity from MillipascalSeconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromMillipascalSeconds(double millipascalseconds) + { + double value = (double) millipascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); + } + /// + /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double newtonsecondspermetersquared) + { + double value = (double) newtonsecondspermetersquared; + return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); + } + /// + /// Get DynamicViscosity from PascalSeconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromPascalSeconds(double pascalseconds) + { + double value = (double) pascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); + } + /// + /// Get DynamicViscosity from Poise. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromPoise(double poise) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) + { + return new DynamicViscosity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 DynamicViscosity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 DynamicViscosity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 DynamicViscosityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..42f0c6faaa --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,621 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 ElectricAdmittance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricAdmittanceUnit? _unit; + + static ElectricAdmittance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Siemens. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricAdmittance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. + /// + public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricAdmittance; + + /// + /// All units of measurement for the ElectricAdmittance quantity. + /// + public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricAdmittance Zero => new ElectricAdmittance(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 ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricAdmittance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricAdmittanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricAdmittance from Microsiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromMicrosiemens(double microsiemens) + { + double value = (double) microsiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); + } + /// + /// Get ElectricAdmittance from Millisiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromMillisiemens(double millisiemens) + { + double value = (double) millisiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); + } + /// + /// Get ElectricAdmittance from Nanosiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromNanosiemens(double nanosiemens) + { + double value = (double) nanosiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); + } + /// + /// Get ElectricAdmittance from Siemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromSiemens(double siemens) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromUnit) + { + return new ElectricAdmittance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricAdmittance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricAdmittance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricAdmittance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricAdmittanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..a3f707e4d3 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electric_charge + /// + // 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 ElectricCharge : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeUnit? _unit; + + static ElectricCharge() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Coulomb. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricCharge() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. + /// + public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCharge; + + /// + /// All units of measurement for the ElectricCharge quantity. + /// + public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. + /// + public static ElectricCharge Zero => new ElectricCharge(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 ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCharge.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCharge in Coulombs. + /// + public double Coulombs => As(ElectricChargeUnit.Coulomb); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCharge from Coulombs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCharge FromCoulombs(double coulombs) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) + { + return new ElectricCharge((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCharge Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCharge result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCharge result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricChargeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricChargeUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..0e81c2f40b --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Charge_density + /// + // 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 ElectricChargeDensity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeDensityUnit? _unit; + + static ElectricChargeDensity() + { + BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit CoulombPerCubicMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricChargeDensity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. + /// + public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricChargeDensity; + + /// + /// All units of measurement for the ElectricChargeDensity quantity. + /// + public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. + /// + public static ElectricChargeDensity Zero => new ElectricChargeDensity(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 ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricChargeDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricChargeDensity in CoulombsPerCubicMeter. + /// + public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricChargeDensity from CoulombsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricChargeDensity FromCoulombsPerCubicMeter(double coulombspercubicmeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit fromUnit) + { + return new ElectricChargeDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricChargeDensity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricChargeDensity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricChargeDensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..17b4739907 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,607 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance + /// + // 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 ElectricConductance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductanceUnit? _unit; + + static ElectricConductance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Siemens. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricConductance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. + /// + public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricConductance; + + /// + /// All units of measurement for the ElectricConductance quantity. + /// + public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricConductance Zero => new ElectricConductance(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 ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricConductance from Microsiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductance FromMicrosiemens(double microsiemens) + { + double value = (double) microsiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); + } + /// + /// Get ElectricConductance from Millisiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductance FromMillisiemens(double millisiemens) + { + double value = (double) millisiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); + } + /// + /// Get ElectricConductance from Siemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductance FromSiemens(double siemens) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricConductance From(double value, ElectricConductanceUnit fromUnit) + { + return new ElectricConductance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricConductance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricConductance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricConductance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricConductanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..5f0854098d --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// + // 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 ElectricConductivity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductivityUnit? _unit; + + static ElectricConductivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit SiemensPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricConductivity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. + /// + public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricConductivity; + + /// + /// All units of measurement for the ElectricConductivity quantity. + /// + public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. + /// + public static ElectricConductivity Zero => new ElectricConductivity(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 ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricConductivity in SiemensPerMeter. + /// + public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricConductivity from SiemensPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductivity FromSiemensPerMeter(double siemenspermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricConductivity From(double value, ElectricConductivityUnit fromUnit) + { + return new ElectricConductivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricConductivity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricConductivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricConductivity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricConductivityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..922de73b93 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs @@ -0,0 +1,689 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ElectricCurrent : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentUnit? _unit; + + static ElectricCurrent() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Ampere. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricCurrent() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. + /// + public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCurrent; + + /// + /// All units of measurement for the ElectricCurrent quantity. + /// + public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. + /// + public static ElectricCurrent Zero => new ElectricCurrent(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 ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrent.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrent from Amperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromAmperes(double amperes) + { + double value = (double) amperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); + } + /// + /// Get ElectricCurrent from Centiamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromCentiamperes(double centiamperes) + { + double value = (double) centiamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); + } + /// + /// Get ElectricCurrent from Kiloamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromKiloamperes(double kiloamperes) + { + double value = (double) kiloamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); + } + /// + /// Get ElectricCurrent from Megaamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromMegaamperes(double megaamperes) + { + double value = (double) megaamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); + } + /// + /// Get ElectricCurrent from Microamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromMicroamperes(double microamperes) + { + double value = (double) microamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); + } + /// + /// Get ElectricCurrent from Milliamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromMilliamperes(double milliamperes) + { + double value = (double) milliamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); + } + /// + /// Get ElectricCurrent from Nanoamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromNanoamperes(double nanoamperes) + { + double value = (double) nanoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); + } + /// + /// Get ElectricCurrent from Picoamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromPicoamperes(double picoamperes) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) + { + return new ElectricCurrent((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCurrent Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCurrent result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricCurrentUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..43963d75d5 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In electromagnetism, current density is the electric current per unit area of cross section. + /// + /// + /// https://en.wikipedia.org/wiki/Current_density + /// + // 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 ElectricCurrentDensity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentDensityUnit? _unit; + + static ElectricCurrentDensity() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit AmperePerSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricCurrentDensity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. + /// + public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCurrentDensity; + + /// + /// All units of measurement for the ElectricCurrentDensity quantity. + /// + public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. + /// + public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(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 ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentDensity in AmperesPerSquareMeter. + /// + public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrentDensity from AmperesPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrentDensity FromAmperesPerSquareMeter(double amperespersquaremeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUnit fromUnit) + { + return new ElectricCurrentDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentDensity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentDensity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricCurrentDensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..88ea70ce25 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs @@ -0,0 +1,570 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In electromagnetism, the current gradient describes how the current changes in time. + /// + // 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 ElectricCurrentGradient : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentGradientUnit? _unit; + + static ElectricCurrentGradient() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit AmperePerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricCurrentGradient() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. + /// + public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCurrentGradient; + + /// + /// All units of measurement for the ElectricCurrentGradient quantity. + /// + public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. + /// + public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(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 ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentGradient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentGradient in AmperesPerSecond. + /// + public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentGradientUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrentGradient from AmperesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrentGradient FromAmperesPerSecond(double amperespersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricCurrentGradient From(double value, ElectricCurrentGradientUnit fromUnit) + { + return new ElectricCurrentGradient((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentGradient Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentGradient result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricCurrentGradientUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..7fc78e14f1 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. + /// + /// + /// https://en.wikipedia.org/wiki/Electric_field + /// + // 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 ElectricField : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricFieldUnit? _unit; + + static ElectricField() + { + BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit VoltPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricField() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. + /// + public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricField; + + /// + /// All units of measurement for the ElectricField quantity. + /// + public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. + /// + public static ElectricField Zero => new ElectricField(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 ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricField in VoltsPerMeter. + /// + public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricFieldUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricField from VoltsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricField FromVoltsPerMeter(double voltspermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricField From(double value, ElectricFieldUnit fromUnit) + { + return new ElectricField((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricField Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricField result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricField result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricFieldUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..903a89b9d4 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Inductance is a property of an electrical conductor which opposes a change in current. + /// + /// + /// https://en.wikipedia.org/wiki/Inductance + /// + // 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 ElectricInductance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricInductanceUnit? _unit; + + static ElectricInductance() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Henry. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricInductance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. + /// + public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricInductance; + + /// + /// All units of measurement for the ElectricInductance quantity. + /// + public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Henry. + /// + public static ElectricInductance Zero => new ElectricInductance(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 ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricInductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricInductance in Henries. + /// + public double Henries => As(ElectricInductanceUnit.Henry); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricInductanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricInductance from Henries. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricInductance FromHenries(double henries) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricInductance From(double value, ElectricInductanceUnit fromUnit) + { + return new ElectricInductance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricInductance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricInductance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricInductance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricInductanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..d908ead398 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs @@ -0,0 +1,638 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ElectricPotential : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialUnit? _unit; + + static ElectricPotential() + { + BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Volt. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricPotential() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. + /// + public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricPotential; + + /// + /// All units of measurement for the ElectricPotential quantity. + /// + public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Volt. + /// + public static ElectricPotential Zero => new ElectricPotential(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 ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotential.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotential from Kilovolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromKilovolts(double kilovolts) + { + double value = (double) kilovolts; + return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); + } + /// + /// Get ElectricPotential from Megavolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromMegavolts(double megavolts) + { + double value = (double) megavolts; + return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); + } + /// + /// Get ElectricPotential from Microvolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromMicrovolts(double microvolts) + { + double value = (double) microvolts; + return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); + } + /// + /// Get ElectricPotential from Millivolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromMillivolts(double millivolts) + { + double value = (double) millivolts; + return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); + } + /// + /// Get ElectricPotential from Volts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromVolts(double volts) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricPotential From(double value, ElectricPotentialUnit fromUnit) + { + return new ElectricPotential((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricPotential Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotential result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricPotential result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricPotentialUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..449568468e --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs @@ -0,0 +1,638 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The Electric Potential of a system known to use Alternating Current. + /// + // 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 ElectricPotentialAc : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialAcUnit? _unit; + + static ElectricPotentialAc() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit VoltAc. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricPotentialAc() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. + /// + public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricPotentialAc; + + /// + /// All units of measurement for the ElectricPotentialAc quantity. + /// + public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. + /// + public static ElectricPotentialAc Zero => new ElectricPotentialAc(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 ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialAc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialAcUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialAc from KilovoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromKilovoltsAc(double kilovoltsac) + { + double value = (double) kilovoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); + } + /// + /// Get ElectricPotentialAc from MegavoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromMegavoltsAc(double megavoltsac) + { + double value = (double) megavoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); + } + /// + /// Get ElectricPotentialAc from MicrovoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromMicrovoltsAc(double microvoltsac) + { + double value = (double) microvoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); + } + /// + /// Get ElectricPotentialAc from MillivoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromMillivoltsAc(double millivoltsac) + { + double value = (double) millivoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); + } + /// + /// Get ElectricPotentialAc from VoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromVoltsAc(double voltsac) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fromUnit) + { + return new ElectricPotentialAc((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialAc Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialAc result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricPotentialAcUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..8d64cf696e --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs @@ -0,0 +1,638 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The Electric Potential of a system known to use Direct Current. + /// + // 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 ElectricPotentialDc : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialDcUnit? _unit; + + static ElectricPotentialDc() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit VoltDc. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricPotentialDc() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. + /// + public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricPotentialDc; + + /// + /// All units of measurement for the ElectricPotentialDc quantity. + /// + public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. + /// + public static ElectricPotentialDc Zero => new ElectricPotentialDc(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 ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialDc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialDcUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialDc from KilovoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromKilovoltsDc(double kilovoltsdc) + { + double value = (double) kilovoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); + } + /// + /// Get ElectricPotentialDc from MegavoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromMegavoltsDc(double megavoltsdc) + { + double value = (double) megavoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); + } + /// + /// Get ElectricPotentialDc from MicrovoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromMicrovoltsDc(double microvoltsdc) + { + double value = (double) microvoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); + } + /// + /// Get ElectricPotentialDc from MillivoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromMillivoltsDc(double millivoltsdc) + { + double value = (double) millivoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); + } + /// + /// Get ElectricPotentialDc from VoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromVoltsDc(double voltsdc) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fromUnit) + { + return new ElectricPotentialDc((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialDc Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialDc result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricPotentialDcUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..7978859d3d --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,621 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ElectricResistance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistanceUnit? _unit; + + static ElectricResistance() + { + BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Ohm. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricResistance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. + /// + public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricResistance; + + /// + /// All units of measurement for the ElectricResistance quantity. + /// + public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. + /// + public static ElectricResistance Zero => new ElectricResistance(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 ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistance from Kiloohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromKiloohms(double kiloohms) + { + double value = (double) kiloohms; + return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); + } + /// + /// Get ElectricResistance from Megaohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromMegaohms(double megaohms) + { + double value = (double) megaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); + } + /// + /// Get ElectricResistance from Milliohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromMilliohms(double milliohms) + { + double value = (double) milliohms; + return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); + } + /// + /// Get ElectricResistance from Ohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromOhms(double ohms) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricResistance From(double value, ElectricResistanceUnit fromUnit) + { + return new ElectricResistance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricResistance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricResistance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricResistance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricResistanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..62a12c9d78 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,624 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// + // 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 ElectricResistivity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistivityUnit? _unit; + + static ElectricResistivity() + { + BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit OhmMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ElectricResistivity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. + /// + public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricResistivity; + + /// + /// All units of measurement for the ElectricResistivity quantity. + /// + public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. + /// + public static ElectricResistivity Zero => new ElectricResistivity(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 ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistivity from MicroohmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromMicroohmMeters(double microohmmeters) + { + double value = (double) microohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); + } + /// + /// Get ElectricResistivity from MilliohmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromMilliohmMeters(double milliohmmeters) + { + double value = (double) milliohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); + } + /// + /// Get ElectricResistivity from NanoohmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromNanoohmMeters(double nanoohmmeters) + { + double value = (double) nanoohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); + } + /// + /// Get ElectricResistivity from OhmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromOhmMeters(double ohmmeters) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricResistivity From(double value, ElectricResistivityUnit fromUnit) + { + return new ElectricResistivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricResistivity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricResistivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricResistivity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricResistivityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..1a019820bd --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,927 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Energy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly EnergyUnit? _unit; + + static Energy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Joule. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Energy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Energy, which is Joule. All conversions go via this value. + /// + public static EnergyUnit BaseUnit => EnergyUnit.Joule; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Energy; + + /// + /// All units of measurement for the Energy quantity. + /// + public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Joule. + /// + public static Energy Zero => new Energy(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 EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Energy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Energy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Energy from BritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromBritishThermalUnits(double britishthermalunits) + { + double value = (double) britishthermalunits; + return new Energy(value, EnergyUnit.BritishThermalUnit); + } + /// + /// Get Energy from Calories. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromCalories(double calories) + { + double value = (double) calories; + return new Energy(value, EnergyUnit.Calorie); + } + /// + /// Get Energy from DecathermsEc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromDecathermsEc(double decathermsec) + { + double value = (double) decathermsec; + return new Energy(value, EnergyUnit.DecathermEc); + } + /// + /// Get Energy from DecathermsImperial. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromDecathermsImperial(double decathermsimperial) + { + double value = (double) decathermsimperial; + return new Energy(value, EnergyUnit.DecathermImperial); + } + /// + /// Get Energy from DecathermsUs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromDecathermsUs(double decathermsus) + { + double value = (double) decathermsus; + return new Energy(value, EnergyUnit.DecathermUs); + } + /// + /// Get Energy from ElectronVolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromElectronVolts(double electronvolts) + { + double value = (double) electronvolts; + return new Energy(value, EnergyUnit.ElectronVolt); + } + /// + /// Get Energy from Ergs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromErgs(double ergs) + { + double value = (double) ergs; + return new Energy(value, EnergyUnit.Erg); + } + /// + /// Get Energy from FootPounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromFootPounds(double footpounds) + { + double value = (double) footpounds; + return new Energy(value, EnergyUnit.FootPound); + } + /// + /// Get Energy from GigabritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromGigabritishThermalUnits(double gigabritishthermalunits) + { + double value = (double) gigabritishthermalunits; + return new Energy(value, EnergyUnit.GigabritishThermalUnit); + } + /// + /// Get Energy from GigawattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromGigawattHours(double gigawatthours) + { + double value = (double) gigawatthours; + return new Energy(value, EnergyUnit.GigawattHour); + } + /// + /// Get Energy from Joules. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromJoules(double joules) + { + double value = (double) joules; + return new Energy(value, EnergyUnit.Joule); + } + /// + /// Get Energy from KilobritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilobritishThermalUnits(double kilobritishthermalunits) + { + double value = (double) kilobritishthermalunits; + return new Energy(value, EnergyUnit.KilobritishThermalUnit); + } + /// + /// Get Energy from Kilocalories. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilocalories(double kilocalories) + { + double value = (double) kilocalories; + return new Energy(value, EnergyUnit.Kilocalorie); + } + /// + /// Get Energy from Kilojoules. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilojoules(double kilojoules) + { + double value = (double) kilojoules; + return new Energy(value, EnergyUnit.Kilojoule); + } + /// + /// Get Energy from KilowattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilowattHours(double kilowatthours) + { + double value = (double) kilowatthours; + return new Energy(value, EnergyUnit.KilowattHour); + } + /// + /// Get Energy from MegabritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromMegabritishThermalUnits(double megabritishthermalunits) + { + double value = (double) megabritishthermalunits; + return new Energy(value, EnergyUnit.MegabritishThermalUnit); + } + /// + /// Get Energy from Megajoules. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromMegajoules(double megajoules) + { + double value = (double) megajoules; + return new Energy(value, EnergyUnit.Megajoule); + } + /// + /// Get Energy from MegawattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromMegawattHours(double megawatthours) + { + double value = (double) megawatthours; + return new Energy(value, EnergyUnit.MegawattHour); + } + /// + /// Get Energy from ThermsEc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromThermsEc(double thermsec) + { + double value = (double) thermsec; + return new Energy(value, EnergyUnit.ThermEc); + } + /// + /// Get Energy from ThermsImperial. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromThermsImperial(double thermsimperial) + { + double value = (double) thermsimperial; + return new Energy(value, EnergyUnit.ThermImperial); + } + /// + /// Get Energy from ThermsUs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromThermsUs(double thermsus) + { + double value = (double) thermsus; + return new Energy(value, EnergyUnit.ThermUs); + } + /// + /// Get Energy from WattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromWattHours(double watthours) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Energy From(double value, EnergyUnit fromUnit) + { + return new Energy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Energy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Energy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Energy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out EnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 EnergyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..5314156dfd --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,672 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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 + /// + // 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 Entropy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly EntropyUnit? _unit; + + static Entropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit JoulePerKelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Entropy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. + /// + public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Entropy; + + /// + /// All units of measurement for the Entropy quantity. + /// + public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. + /// + public static Entropy Zero => new Entropy(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 EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Entropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Entropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EntropyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Entropy from CaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromCaloriesPerKelvin(double caloriesperkelvin) + { + double value = (double) caloriesperkelvin; + return new Entropy(value, EntropyUnit.CaloriePerKelvin); + } + /// + /// Get Entropy from JoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromJoulesPerDegreeCelsius(double joulesperdegreecelsius) + { + double value = (double) joulesperdegreecelsius; + return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); + } + /// + /// Get Entropy from JoulesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromJoulesPerKelvin(double joulesperkelvin) + { + double value = (double) joulesperkelvin; + return new Entropy(value, EntropyUnit.JoulePerKelvin); + } + /// + /// Get Entropy from KilocaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromKilocaloriesPerKelvin(double kilocaloriesperkelvin) + { + double value = (double) kilocaloriesperkelvin; + return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); + } + /// + /// Get Entropy from KilojoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromKilojoulesPerDegreeCelsius(double kilojoulesperdegreecelsius) + { + double value = (double) kilojoulesperdegreecelsius; + return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); + } + /// + /// Get Entropy from KilojoulesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromKilojoulesPerKelvin(double kilojoulesperkelvin) + { + double value = (double) kilojoulesperkelvin; + return new Entropy(value, EntropyUnit.KilojoulePerKelvin); + } + /// + /// Get Entropy from MegajoulesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromMegajoulesPerKelvin(double megajoulesperkelvin) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Entropy From(double value, EntropyUnit fromUnit) + { + return new Entropy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Entropy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Entropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Entropy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out EntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 EntropyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..bbeb01758b --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs @@ -0,0 +1,774 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Force : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceUnit? _unit; + + static Force() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Newton. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Force() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Force, which is Newton. All conversions go via this value. + /// + public static ForceUnit BaseUnit => ForceUnit.Newton; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Force; + + /// + /// All units of measurement for the Force quantity. + /// + public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Newton. + /// + public static Force Zero => new Force(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 ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Force.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Force.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Micronewtons. + /// + public double Micronewtons => As(ForceUnit.Micronewton); + + /// + /// Get Force in Millinewtons. + /// + public double Millinewtons => As(ForceUnit.Millinewton); + + /// + /// Get Force in Newtons. + /// + public double Newtons => As(ForceUnit.Newton); + + /// + /// Get Force in OunceForce. + /// + public double OunceForce => As(ForceUnit.OunceForce); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ForceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Force from Decanewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromDecanewtons(double decanewtons) + { + double value = (double) decanewtons; + return new Force(value, ForceUnit.Decanewton); + } + /// + /// Get Force from Dyne. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromDyne(double dyne) + { + double value = (double) dyne; + return new Force(value, ForceUnit.Dyn); + } + /// + /// Get Force from KilogramsForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromKilogramsForce(double kilogramsforce) + { + double value = (double) kilogramsforce; + return new Force(value, ForceUnit.KilogramForce); + } + /// + /// Get Force from Kilonewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromKilonewtons(double kilonewtons) + { + double value = (double) kilonewtons; + return new Force(value, ForceUnit.Kilonewton); + } + /// + /// Get Force from KiloPonds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromKiloPonds(double kiloponds) + { + double value = (double) kiloponds; + return new Force(value, ForceUnit.KiloPond); + } + /// + /// Get Force from Meganewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromMeganewtons(double meganewtons) + { + double value = (double) meganewtons; + return new Force(value, ForceUnit.Meganewton); + } + /// + /// Get Force from Micronewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromMicronewtons(double micronewtons) + { + double value = (double) micronewtons; + return new Force(value, ForceUnit.Micronewton); + } + /// + /// Get Force from Millinewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromMillinewtons(double millinewtons) + { + double value = (double) millinewtons; + return new Force(value, ForceUnit.Millinewton); + } + /// + /// Get Force from Newtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromNewtons(double newtons) + { + double value = (double) newtons; + return new Force(value, ForceUnit.Newton); + } + /// + /// Get Force from OunceForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromOunceForce(double ounceforce) + { + double value = (double) ounceforce; + return new Force(value, ForceUnit.OunceForce); + } + /// + /// Get Force from Poundals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromPoundals(double poundals) + { + double value = (double) poundals; + return new Force(value, ForceUnit.Poundal); + } + /// + /// Get Force from PoundsForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromPoundsForce(double poundsforce) + { + double value = (double) poundsforce; + return new Force(value, ForceUnit.PoundForce); + } + /// + /// Get Force from TonnesForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromTonnesForce(double tonnesforce) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Force From(double value, ForceUnit fromUnit) + { + return new Force((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Force Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Force result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Force result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ForceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.Micronewton: return (_value) * 1e-6d; + case ForceUnit.Millinewton: return (_value) * 1e-3d; + case ForceUnit.Newton: return _value; + case ForceUnit.OunceForce: return _value*2.780138509537812e-1; + 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.Micronewton: return (baseUnitValue) / 1e-6d; + case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; + case ForceUnit.Newton: return baseUnitValue; + case ForceUnit.OunceForce: return baseUnitValue/2.780138509537812e-1; + 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..0c46661ff2 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs @@ -0,0 +1,740 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 ForceChangeRate : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceChangeRateUnit? _unit; + + static ForceChangeRate() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ForceChangeRate() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. + /// + public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ForceChangeRate; + + /// + /// All units of measurement for the ForceChangeRate quantity. + /// + public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. + /// + public static ForceChangeRate Zero => new ForceChangeRate(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 ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForceChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ForceChangeRate from CentinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromCentinewtonsPerSecond(double centinewtonspersecond) + { + double value = (double) centinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); + } + /// + /// Get ForceChangeRate from DecanewtonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromDecanewtonsPerMinute(double decanewtonsperminute) + { + double value = (double) decanewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); + } + /// + /// Get ForceChangeRate from DecanewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromDecanewtonsPerSecond(double decanewtonspersecond) + { + double value = (double) decanewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); + } + /// + /// Get ForceChangeRate from DecinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromDecinewtonsPerSecond(double decinewtonspersecond) + { + double value = (double) decinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); + } + /// + /// Get ForceChangeRate from KilonewtonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromKilonewtonsPerMinute(double kilonewtonsperminute) + { + double value = (double) kilonewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); + } + /// + /// Get ForceChangeRate from KilonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromKilonewtonsPerSecond(double kilonewtonspersecond) + { + double value = (double) kilonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); + } + /// + /// Get ForceChangeRate from MicronewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromMicronewtonsPerSecond(double micronewtonspersecond) + { + double value = (double) micronewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); + } + /// + /// Get ForceChangeRate from MillinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromMillinewtonsPerSecond(double millinewtonspersecond) + { + double value = (double) millinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); + } + /// + /// Get ForceChangeRate from NanonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromNanonewtonsPerSecond(double nanonewtonspersecond) + { + double value = (double) nanonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); + } + /// + /// Get ForceChangeRate from NewtonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromNewtonsPerMinute(double newtonsperminute) + { + double value = (double) newtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); + } + /// + /// Get ForceChangeRate from NewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromNewtonsPerSecond(double newtonspersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) + { + return new ForceChangeRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ForceChangeRate Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ForceChangeRate result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ForceChangeRateUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..05c3e249b4 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs @@ -0,0 +1,706 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The magnitude of force per unit length. + /// + // 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 ForcePerLength : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForcePerLengthUnit? _unit; + + static ForcePerLength() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ForcePerLength() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. + /// + public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ForcePerLength; + + /// + /// All units of measurement for the ForcePerLength quantity. + /// + public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. + /// + public static ForcePerLength Zero => new ForcePerLength(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 ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForcePerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForcePerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ForcePerLength from CentinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromCentinewtonsPerMeter(double centinewtonspermeter) + { + double value = (double) centinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); + } + /// + /// Get ForcePerLength from DecinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromDecinewtonsPerMeter(double decinewtonspermeter) + { + double value = (double) decinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); + } + /// + /// Get ForcePerLength from KilogramsForcePerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromKilogramsForcePerMeter(double kilogramsforcepermeter) + { + double value = (double) kilogramsforcepermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); + } + /// + /// Get ForcePerLength from KilonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromKilonewtonsPerMeter(double kilonewtonspermeter) + { + double value = (double) kilonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); + } + /// + /// Get ForcePerLength from MeganewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromMeganewtonsPerMeter(double meganewtonspermeter) + { + double value = (double) meganewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); + } + /// + /// Get ForcePerLength from MicronewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromMicronewtonsPerMeter(double micronewtonspermeter) + { + double value = (double) micronewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); + } + /// + /// Get ForcePerLength from MillinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromMillinewtonsPerMeter(double millinewtonspermeter) + { + double value = (double) millinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); + } + /// + /// Get ForcePerLength from NanonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromNanonewtonsPerMeter(double nanonewtonspermeter) + { + double value = (double) nanonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); + } + /// + /// Get ForcePerLength from NewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromNewtonsPerMeter(double newtonspermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) + { + return new ForcePerLength((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ForcePerLength Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ForcePerLength result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ForcePerLength result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ForcePerLengthUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..5822efad71 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs @@ -0,0 +1,689 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The number of occurrences of a repeating event per unit time. + /// + // 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 Frequency : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FrequencyUnit? _unit; + + static Frequency() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Hertz. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Frequency() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Frequency, which is Hertz. All conversions go via this value. + /// + public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Frequency; + + /// + /// All units of measurement for the Frequency quantity. + /// + public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. + /// + public static Frequency Zero => new Frequency(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 FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Frequency.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Frequency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(FrequencyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Frequency from CyclesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromCyclesPerHour(double cyclesperhour) + { + double value = (double) cyclesperhour; + return new Frequency(value, FrequencyUnit.CyclePerHour); + } + /// + /// Get Frequency from CyclesPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromCyclesPerMinute(double cyclesperminute) + { + double value = (double) cyclesperminute; + return new Frequency(value, FrequencyUnit.CyclePerMinute); + } + /// + /// Get Frequency from Gigahertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromGigahertz(double gigahertz) + { + double value = (double) gigahertz; + return new Frequency(value, FrequencyUnit.Gigahertz); + } + /// + /// Get Frequency from Hertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromHertz(double hertz) + { + double value = (double) hertz; + return new Frequency(value, FrequencyUnit.Hertz); + } + /// + /// Get Frequency from Kilohertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromKilohertz(double kilohertz) + { + double value = (double) kilohertz; + return new Frequency(value, FrequencyUnit.Kilohertz); + } + /// + /// Get Frequency from Megahertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromMegahertz(double megahertz) + { + double value = (double) megahertz; + return new Frequency(value, FrequencyUnit.Megahertz); + } + /// + /// Get Frequency from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromRadiansPerSecond(double radianspersecond) + { + double value = (double) radianspersecond; + return new Frequency(value, FrequencyUnit.RadianPerSecond); + } + /// + /// Get Frequency from Terahertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromTerahertz(double terahertz) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Frequency From(double value, FrequencyUnit fromUnit) + { + return new Frequency((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Frequency Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Frequency result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Frequency result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out FrequencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 FrequencyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..408b7d2c64 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs @@ -0,0 +1,825 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Heat flux is the flow of energy per unit of area per unit of time + /// + // 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 HeatFlux : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatFluxUnit? _unit; + + static HeatFlux() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public HeatFlux() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. + /// + public static HeatFluxUnit BaseUnit => HeatFluxUnit.WattPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.HeatFlux; + + /// + /// All units of measurement for the HeatFlux quantity. + /// + public static HeatFluxUnit[] Units { get; } = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static HeatFlux Zero => new HeatFlux(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 HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get HeatFlux from BtusPerHourSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerHourSquareFoot(double btusperhoursquarefoot) + { + double value = (double) btusperhoursquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); + } + /// + /// Get HeatFlux from BtusPerMinuteSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerMinuteSquareFoot(double btusperminutesquarefoot) + { + double value = (double) btusperminutesquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); + } + /// + /// Get HeatFlux from BtusPerSecondSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerSecondSquareFoot(double btuspersecondsquarefoot) + { + double value = (double) btuspersecondsquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); + } + /// + /// Get HeatFlux from BtusPerSecondSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerSecondSquareInch(double btuspersecondsquareinch) + { + double value = (double) btuspersecondsquareinch; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); + } + /// + /// Get HeatFlux from CaloriesPerSecondSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double caloriespersecondsquarecentimeter) + { + double value = (double) caloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); + } + /// + /// Get HeatFlux from CentiwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromCentiwattsPerSquareMeter(double centiwattspersquaremeter) + { + double value = (double) centiwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); + } + /// + /// Get HeatFlux from DeciwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromDeciwattsPerSquareMeter(double deciwattspersquaremeter) + { + double value = (double) deciwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); + } + /// + /// Get HeatFlux from KilocaloriesPerHourSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromKilocaloriesPerHourSquareMeter(double kilocaloriesperhoursquaremeter) + { + double value = (double) kilocaloriesperhoursquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); + } + /// + /// Get HeatFlux from KilocaloriesPerSecondSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double kilocaloriespersecondsquarecentimeter) + { + double value = (double) kilocaloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + } + /// + /// Get HeatFlux from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromKilowattsPerSquareMeter(double kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); + } + /// + /// Get HeatFlux from MicrowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromMicrowattsPerSquareMeter(double microwattspersquaremeter) + { + double value = (double) microwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); + } + /// + /// Get HeatFlux from MilliwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) + { + double value = (double) milliwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); + } + /// + /// Get HeatFlux from NanowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromNanowattsPerSquareMeter(double nanowattspersquaremeter) + { + double value = (double) nanowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); + } + /// + /// Get HeatFlux from WattsPerSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromWattsPerSquareFoot(double wattspersquarefoot) + { + double value = (double) wattspersquarefoot; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); + } + /// + /// Get HeatFlux from WattsPerSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromWattsPerSquareInch(double wattspersquareinch) + { + double value = (double) wattspersquareinch; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); + } + /// + /// Get HeatFlux from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromWattsPerSquareMeter(double wattspersquaremeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static HeatFlux From(double value, HeatFluxUnit fromUnit) + { + return new HeatFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 HeatFlux Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out HeatFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 HeatFlux result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 HeatFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out HeatFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 HeatFluxUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..49fa0395d2 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs @@ -0,0 +1,587 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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) + /// + // 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 HeatTransferCoefficient : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatTransferCoefficientUnit? _unit; + + static HeatTransferCoefficient() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public HeatTransferCoefficient() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. + /// + public static HeatTransferCoefficientUnit BaseUnit => HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.HeatTransferCoefficient; + + /// + /// All units of measurement for the HeatTransferCoefficient quantity. + /// + public static HeatTransferCoefficientUnit[] Units { get; } = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. + /// + public static HeatTransferCoefficient Zero => new HeatTransferCoefficient(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 HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatTransferCoefficient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterCelsius. + /// + public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterKelvin. + /// + public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatTransferCoefficientUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double wattspersquaremetercelsius) + { + double value = (double) wattspersquaremetercelsius; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + } + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double wattspersquaremeterkelvin) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static HeatTransferCoefficient From(double value, HeatTransferCoefficientUnit fromUnit) + { + return new HeatTransferCoefficient((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 HeatTransferCoefficient Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out HeatTransferCoefficient result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 HeatTransferCoefficient result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 HeatTransferCoefficientUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 HeatTransferCoefficientUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..87cc96ecbd --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,624 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. + /// + /// + /// https://en.wikipedia.org/wiki/Illuminance + /// + // 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 Illuminance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IlluminanceUnit? _unit; + + static Illuminance() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + } + /// + /// Creates the quantity with a value of 0 in the base unit Lux. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Illuminance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Illuminance, which is Lux. All conversions go via this value. + /// + public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Illuminance; + + /// + /// All units of measurement for the Illuminance quantity. + /// + public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lux. + /// + public static Illuminance Zero => new Illuminance(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 IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Illuminance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Illuminance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IlluminanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Illuminance from Kilolux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromKilolux(double kilolux) + { + double value = (double) kilolux; + return new Illuminance(value, IlluminanceUnit.Kilolux); + } + /// + /// Get Illuminance from Lux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromLux(double lux) + { + double value = (double) lux; + return new Illuminance(value, IlluminanceUnit.Lux); + } + /// + /// Get Illuminance from Megalux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromMegalux(double megalux) + { + double value = (double) megalux; + return new Illuminance(value, IlluminanceUnit.Megalux); + } + /// + /// Get Illuminance from Millilux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromMillilux(double millilux) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Illuminance From(double value, IlluminanceUnit fromUnit) + { + return new Illuminance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Illuminance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Illuminance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Illuminance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IlluminanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 IlluminanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..87bee65bf0 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,587 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. + /// + // 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 Irradiance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradianceUnit? _unit; + + static Irradiance() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Irradiance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. + /// + public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Irradiance; + + /// + /// All units of measurement for the Irradiance quantity. + /// + public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static Irradiance Zero => new Irradiance(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 IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Irradiance in KilowattsPerSquareMeter. + /// + public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + + /// + /// Get Irradiance in WattsPerSquareMeter. + /// + public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradianceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiance from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); + } + /// + /// Get Irradiance from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Irradiance From(double value, IrradianceUnit fromUnit) + { + return new Irradiance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Irradiance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Irradiance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Irradiance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IrradianceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 IrradianceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..9478a879a7 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs @@ -0,0 +1,607 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Irradiation + /// + // 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 Irradiation : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradiationUnit? _unit; + + static Irradiation() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit JoulePerSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Irradiation() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. + /// + public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Irradiation; + + /// + /// All units of measurement for the Irradiation quantity. + /// + public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. + /// + public static Irradiation Zero => new Irradiation(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 IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiation.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiation.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradiationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiation from JoulesPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiation FromJoulesPerSquareMeter(double joulespersquaremeter) + { + double value = (double) joulespersquaremeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); + } + /// + /// Get Irradiation from KilowattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiation FromKilowattHoursPerSquareMeter(double kilowatthourspersquaremeter) + { + double value = (double) kilowatthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); + } + /// + /// Get Irradiation from WattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiation FromWattHoursPerSquareMeter(double watthourspersquaremeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Irradiation From(double value, IrradiationUnit fromUnit) + { + return new Irradiation((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Irradiation Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Irradiation result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Irradiation result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IrradiationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 IrradiationUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..cfc7afe804 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,692 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// http://en.wikipedia.org/wiki/Viscosity + /// + // 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 KinematicViscosity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly KinematicViscosityUnit? _unit; + + static KinematicViscosity() + { + BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit SquareMeterPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public KinematicViscosity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. + /// + public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.KinematicViscosity; + + /// + /// All units of measurement for the KinematicViscosity quantity. + /// + public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. + /// + public static KinematicViscosity Zero => new KinematicViscosity(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 KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => KinematicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(KinematicViscosityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get KinematicViscosity from Centistokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromCentistokes(double centistokes) + { + double value = (double) centistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); + } + /// + /// Get KinematicViscosity from Decistokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromDecistokes(double decistokes) + { + double value = (double) decistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); + } + /// + /// Get KinematicViscosity from Kilostokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromKilostokes(double kilostokes) + { + double value = (double) kilostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); + } + /// + /// Get KinematicViscosity from Microstokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromMicrostokes(double microstokes) + { + double value = (double) microstokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); + } + /// + /// Get KinematicViscosity from Millistokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromMillistokes(double millistokes) + { + double value = (double) millistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); + } + /// + /// Get KinematicViscosity from Nanostokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromNanostokes(double nanostokes) + { + double value = (double) nanostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); + } + /// + /// Get KinematicViscosity from SquareMetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromSquareMetersPerSecond(double squaremeterspersecond) + { + double value = (double) squaremeterspersecond; + return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); + } + /// + /// Get KinematicViscosity from Stokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromStokes(double stokes) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static KinematicViscosity From(double value, KinematicViscosityUnit fromUnit) + { + return new KinematicViscosity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 KinematicViscosity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out KinematicViscosity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 KinematicViscosity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 KinematicViscosityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..f622b8d710 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs @@ -0,0 +1,570 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 LapseRate : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LapseRateUnit? _unit; + + static LapseRate() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public LapseRate() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value. + /// + public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LapseRate; + + /// + /// All units of measurement for the LapseRate quantity. + /// + public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. + /// + public static LapseRate Zero => new LapseRate(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 LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LapseRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LapseRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LapseRate in DegreesCelciusPerKilometer. + /// + public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LapseRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LapseRate from DegreesCelciusPerKilometer. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LapseRate FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static LapseRate From(double value, LapseRateUnit fromUnit) + { + return new LapseRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LapseRate Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LapseRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LapseRate result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LapseRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LapseRateUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..7cfa3a7f33 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,607 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// http://en.wikipedia.org/wiki/Linear_density + /// + // 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 LinearDensity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LinearDensityUnit? _unit; + + static LinearDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public LinearDensity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. + /// + public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LinearDensity; + + /// + /// All units of measurement for the LinearDensity quantity. + /// + public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. + /// + public static LinearDensity Zero => new LinearDensity(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 LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LinearDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LinearDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LinearDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LinearDensity from GramsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LinearDensity FromGramsPerMeter(double gramspermeter) + { + double value = (double) gramspermeter; + return new LinearDensity(value, LinearDensityUnit.GramPerMeter); + } + /// + /// Get LinearDensity from KilogramsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LinearDensity FromKilogramsPerMeter(double kilogramspermeter) + { + double value = (double) kilogramspermeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); + } + /// + /// Get LinearDensity from PoundsPerFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LinearDensity FromPoundsPerFoot(double poundsperfoot) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static LinearDensity From(double value, LinearDensityUnit fromUnit) + { + return new LinearDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LinearDensity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LinearDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LinearDensity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LinearDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LinearDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LinearDensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..7188f7cd59 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. + /// + /// + /// https://en.wikipedia.org/wiki/Luminous_flux + /// + // 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 LuminousFlux : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousFluxUnit? _unit; + + static LuminousFlux() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + } + /// + /// Creates the quantity with a value of 0 in the base unit Lumen. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public LuminousFlux() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. + /// + public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LuminousFlux; + + /// + /// All units of measurement for the LuminousFlux quantity. + /// + public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. + /// + public static LuminousFlux Zero => new LuminousFlux(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 LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousFlux in Lumens. + /// + public double Lumens => As(LuminousFluxUnit.Lumen); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LuminousFlux from Lumens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LuminousFlux FromLumens(double lumens) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) + { + return new LuminousFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LuminousFlux Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LuminousFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LuminousFlux result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LuminousFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LuminousFluxUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..0ae059bf84 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Luminous_intensity + /// + // 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 LuminousIntensity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousIntensityUnit? _unit; + + static LuminousIntensity() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + } + /// + /// Creates the quantity with a value of 0 in the base unit Candela. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public LuminousIntensity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. + /// + public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LuminousIntensity; + + /// + /// All units of measurement for the LuminousIntensity quantity. + /// + public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Candela. + /// + public static LuminousIntensity Zero => new LuminousIntensity(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 LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousIntensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousIntensity in Candela. + /// + public double Candela => As(LuminousIntensityUnit.Candela); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousIntensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LuminousIntensity from Candela. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LuminousIntensity FromCandela(double candela) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static LuminousIntensity From(double value, LuminousIntensityUnit fromUnit) + { + return new LuminousIntensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LuminousIntensity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LuminousIntensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LuminousIntensity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LuminousIntensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..543d738511 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Magnetic_field + /// + // 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 MagneticField : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFieldUnit? _unit; + + static MagneticField() + { + BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Tesla. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MagneticField() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticField, which is Tesla. All conversions go via this value. + /// + public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MagneticField; + + /// + /// All units of measurement for the MagneticField quantity. + /// + public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. + /// + public static MagneticField Zero => new MagneticField(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 MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticField in Teslas. + /// + public double Teslas => As(MagneticFieldUnit.Tesla); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFieldUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MagneticField from Teslas. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MagneticField FromTeslas(double teslas) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MagneticField From(double value, MagneticFieldUnit fromUnit) + { + return new MagneticField((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MagneticField Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MagneticField result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MagneticField result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MagneticFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagneticFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MagneticFieldUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..bc7a0ff539 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Magnetic_flux + /// + // 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 MagneticFlux : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFluxUnit? _unit; + + static MagneticFlux() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Weber. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MagneticFlux() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. + /// + public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MagneticFlux; + + /// + /// All units of measurement for the MagneticFlux quantity. + /// + public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Weber. + /// + public static MagneticFlux Zero => new MagneticFlux(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 MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticFlux in Webers. + /// + public double Webers => As(MagneticFluxUnit.Weber); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MagneticFlux from Webers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MagneticFlux FromWebers(double webers) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) + { + return new MagneticFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MagneticFlux Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MagneticFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MagneticFlux result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagneticFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MagneticFluxUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..ba3a41139d --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Magnetization + /// + // 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 Magnetization : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagnetizationUnit? _unit; + + static Magnetization() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit AmperePerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Magnetization() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. + /// + public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Magnetization; + + /// + /// All units of measurement for the Magnetization quantity. + /// + public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. + /// + public static Magnetization Zero => new Magnetization(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 MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Magnetization.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Magnetization.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Magnetization in AmperesPerMeter. + /// + public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagnetizationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Magnetization from AmperesPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Magnetization FromAmperesPerMeter(double amperespermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Magnetization From(double value, MagnetizationUnit fromUnit) + { + return new Magnetization((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Magnetization Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Magnetization result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Magnetization result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MagnetizationUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagnetizationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MagnetizationUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..30fb8adb4f --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs @@ -0,0 +1,927 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 Mass : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassUnit? _unit; + + static Mass() + { + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Kilogram. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Mass() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Mass, which is Kilogram. All conversions go via this value. + /// + public static MassUnit BaseUnit => MassUnit.Kilogram; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Mass; + + /// + /// All units of measurement for the Mass quantity. + /// + public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. + /// + public static Mass Zero => new Mass(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 MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Mass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Mass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MassUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Mass from Centigrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromCentigrams(double centigrams) + { + double value = (double) centigrams; + return new Mass(value, MassUnit.Centigram); + } + /// + /// Get Mass from Decagrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromDecagrams(double decagrams) + { + double value = (double) decagrams; + return new Mass(value, MassUnit.Decagram); + } + /// + /// Get Mass from Decigrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromDecigrams(double decigrams) + { + double value = (double) decigrams; + return new Mass(value, MassUnit.Decigram); + } + /// + /// Get Mass from Grams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromGrams(double grams) + { + double value = (double) grams; + return new Mass(value, MassUnit.Gram); + } + /// + /// Get Mass from Hectograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromHectograms(double hectograms) + { + double value = (double) hectograms; + return new Mass(value, MassUnit.Hectogram); + } + /// + /// Get Mass from Kilograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromKilograms(double kilograms) + { + double value = (double) kilograms; + return new Mass(value, MassUnit.Kilogram); + } + /// + /// Get Mass from Kilopounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromKilopounds(double kilopounds) + { + double value = (double) kilopounds; + return new Mass(value, MassUnit.Kilopound); + } + /// + /// Get Mass from Kilotonnes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromKilotonnes(double kilotonnes) + { + double value = (double) kilotonnes; + return new Mass(value, MassUnit.Kilotonne); + } + /// + /// Get Mass from LongHundredweight. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromLongHundredweight(double longhundredweight) + { + double value = (double) longhundredweight; + return new Mass(value, MassUnit.LongHundredweight); + } + /// + /// Get Mass from LongTons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromLongTons(double longtons) + { + double value = (double) longtons; + return new Mass(value, MassUnit.LongTon); + } + /// + /// Get Mass from Megapounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMegapounds(double megapounds) + { + double value = (double) megapounds; + return new Mass(value, MassUnit.Megapound); + } + /// + /// Get Mass from Megatonnes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMegatonnes(double megatonnes) + { + double value = (double) megatonnes; + return new Mass(value, MassUnit.Megatonne); + } + /// + /// Get Mass from Micrograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMicrograms(double micrograms) + { + double value = (double) micrograms; + return new Mass(value, MassUnit.Microgram); + } + /// + /// Get Mass from Milligrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMilligrams(double milligrams) + { + double value = (double) milligrams; + return new Mass(value, MassUnit.Milligram); + } + /// + /// Get Mass from Nanograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromNanograms(double nanograms) + { + double value = (double) nanograms; + return new Mass(value, MassUnit.Nanogram); + } + /// + /// Get Mass from Ounces. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromOunces(double ounces) + { + double value = (double) ounces; + return new Mass(value, MassUnit.Ounce); + } + /// + /// Get Mass from Pounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromPounds(double pounds) + { + double value = (double) pounds; + return new Mass(value, MassUnit.Pound); + } + /// + /// Get Mass from ShortHundredweight. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromShortHundredweight(double shorthundredweight) + { + double value = (double) shorthundredweight; + return new Mass(value, MassUnit.ShortHundredweight); + } + /// + /// Get Mass from ShortTons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromShortTons(double shorttons) + { + double value = (double) shorttons; + return new Mass(value, MassUnit.ShortTon); + } + /// + /// Get Mass from Slugs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromSlugs(double slugs) + { + double value = (double) slugs; + return new Mass(value, MassUnit.Slug); + } + /// + /// Get Mass from Stone. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromStone(double stone) + { + double value = (double) stone; + return new Mass(value, MassUnit.Stone); + } + /// + /// Get Mass from Tonnes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromTonnes(double tonnes) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Mass From(double value, MassUnit fromUnit) + { + return new Mass((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Mass Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Mass result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Mass result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..b4fd71ac29 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs @@ -0,0 +1,842 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 MassFlow : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFlowUnit? _unit; + + static MassFlow() + { + BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit GramPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MassFlow() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. + /// + public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MassFlow; + + /// + /// All units of measurement for the MassFlow quantity. + /// + public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. + /// + public static MassFlow Zero => new MassFlow(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 MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 MegapoundsPerMinute. + /// + public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + + /// + /// 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 PoundsPerMinute. + /// + public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFlowUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassFlow from CentigramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromCentigramsPerSecond(double centigramspersecond) + { + double value = (double) centigramspersecond; + return new MassFlow(value, MassFlowUnit.CentigramPerSecond); + } + /// + /// Get MassFlow from DecagramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromDecagramsPerSecond(double decagramspersecond) + { + double value = (double) decagramspersecond; + return new MassFlow(value, MassFlowUnit.DecagramPerSecond); + } + /// + /// Get MassFlow from DecigramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromDecigramsPerSecond(double decigramspersecond) + { + double value = (double) decigramspersecond; + return new MassFlow(value, MassFlowUnit.DecigramPerSecond); + } + /// + /// Get MassFlow from GramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromGramsPerSecond(double gramspersecond) + { + double value = (double) gramspersecond; + return new MassFlow(value, MassFlowUnit.GramPerSecond); + } + /// + /// Get MassFlow from HectogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromHectogramsPerSecond(double hectogramspersecond) + { + double value = (double) hectogramspersecond; + return new MassFlow(value, MassFlowUnit.HectogramPerSecond); + } + /// + /// Get MassFlow from KilogramsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromKilogramsPerHour(double kilogramsperhour) + { + double value = (double) kilogramsperhour; + return new MassFlow(value, MassFlowUnit.KilogramPerHour); + } + /// + /// Get MassFlow from KilogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromKilogramsPerSecond(double kilogramspersecond) + { + double value = (double) kilogramspersecond; + return new MassFlow(value, MassFlowUnit.KilogramPerSecond); + } + /// + /// Get MassFlow from MegapoundsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMegapoundsPerHour(double megapoundsperhour) + { + double value = (double) megapoundsperhour; + return new MassFlow(value, MassFlowUnit.MegapoundPerHour); + } + /// + /// Get MassFlow from MegapoundsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMegapoundsPerMinute(double megapoundsperminute) + { + double value = (double) megapoundsperminute; + return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); + } + /// + /// Get MassFlow from MicrogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMicrogramsPerSecond(double microgramspersecond) + { + double value = (double) microgramspersecond; + return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); + } + /// + /// Get MassFlow from MilligramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMilligramsPerSecond(double milligramspersecond) + { + double value = (double) milligramspersecond; + return new MassFlow(value, MassFlowUnit.MilligramPerSecond); + } + /// + /// Get MassFlow from NanogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromNanogramsPerSecond(double nanogramspersecond) + { + double value = (double) nanogramspersecond; + return new MassFlow(value, MassFlowUnit.NanogramPerSecond); + } + /// + /// Get MassFlow from PoundsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromPoundsPerHour(double poundsperhour) + { + double value = (double) poundsperhour; + return new MassFlow(value, MassFlowUnit.PoundPerHour); + } + /// + /// Get MassFlow from PoundsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromPoundsPerMinute(double poundsperminute) + { + double value = (double) poundsperminute; + return new MassFlow(value, MassFlowUnit.PoundPerMinute); + } + /// + /// Get MassFlow from ShortTonsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromShortTonsPerHour(double shorttonsperhour) + { + double value = (double) shorttonsperhour; + return new MassFlow(value, MassFlowUnit.ShortTonPerHour); + } + /// + /// Get MassFlow from TonnesPerDay. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromTonnesPerDay(double tonnesperday) + { + double value = (double) tonnesperday; + return new MassFlow(value, MassFlowUnit.TonnePerDay); + } + /// + /// Get MassFlow from TonnesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromTonnesPerHour(double tonnesperhour) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MassFlow From(double value, MassFlowUnit fromUnit) + { + return new MassFlow((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MassFlow Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassFlow result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MassFlow result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassFlowUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.MegapoundPerMinute: return (_value/0.132277) * 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.PoundPerMinute: return _value/0.132277; + 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.MegapoundPerMinute: return (baseUnitValue*0.132277) / 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.PoundPerMinute: return baseUnitValue*0.132277; + 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..c8a81c7e16 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs @@ -0,0 +1,587 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Mass flux is the mass flow rate per unit area. + /// + // 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 MassFlux : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFluxUnit? _unit; + + static MassFlux() + { + BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MassFlux() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. + /// + public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MassFlux; + + /// + /// All units of measurement for the MassFlux quantity. + /// + public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. + /// + public static MassFlux Zero => new MassFlux(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 MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassFlux in GramsPerSecondPerSquareMeter. + /// + public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + + /// + /// Get MassFlux in KilogramsPerSecondPerSquareMeter. + /// + public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassFlux from GramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlux FromGramsPerSecondPerSquareMeter(double gramspersecondpersquaremeter) + { + double value = (double) gramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); + } + /// + /// Get MassFlux from KilogramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlux FromKilogramsPerSecondPerSquareMeter(double kilogramspersecondpersquaremeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MassFlux From(double value, MassFluxUnit fromUnit) + { + return new MassFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MassFlux Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MassFlux result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassFluxUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..9e86954cad --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs @@ -0,0 +1,1029 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// A property of body reflects how its mass is distributed with regard to an axis. + /// + // 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 MassMomentOfInertia : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassMomentOfInertiaUnit? _unit; + + static MassMomentOfInertia() + { + BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramSquareMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MassMomentOfInertia() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. + /// + public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MassMomentOfInertia; + + /// + /// All units of measurement for the MassMomentOfInertia quantity. + /// + public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. + /// + public static MassMomentOfInertia Zero => new MassMomentOfInertia(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 MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassMomentOfInertiaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassMomentOfInertia from GramSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareCentimeters(double gramsquarecentimeters) + { + double value = (double) gramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from GramSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareDecimeters(double gramsquaredecimeters) + { + double value = (double) gramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from GramSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareMeters(double gramsquaremeters) + { + double value = (double) gramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); + } + /// + /// Get MassMomentOfInertia from GramSquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareMillimeters(double gramsquaremillimeters) + { + double value = (double) gramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareCentimeters(double kilogramsquarecentimeters) + { + double value = (double) kilogramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareDecimeters(double kilogramsquaredecimeters) + { + double value = (double) kilogramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareMeters(double kilogramsquaremeters) + { + double value = (double) kilogramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareMillimeters(double kilogramsquaremillimeters) + { + double value = (double) kilogramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareCentimeters(double kilotonnesquarecentimeters) + { + double value = (double) kilotonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareDecimeters(double kilotonnesquaredecimeters) + { + double value = (double) kilotonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareMeters(double kilotonnesquaremeters) + { + double value = (double) kilotonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareMilimeters(double kilotonnesquaremilimeters) + { + double value = (double) kilotonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareCentimeters(double megatonnesquarecentimeters) + { + double value = (double) megatonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareDecimeters(double megatonnesquaredecimeters) + { + double value = (double) megatonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareMeters(double megatonnesquaremeters) + { + double value = (double) megatonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareMilimeters(double megatonnesquaremilimeters) + { + double value = (double) megatonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareCentimeters(double milligramsquarecentimeters) + { + double value = (double) milligramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareDecimeters(double milligramsquaredecimeters) + { + double value = (double) milligramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareMeters(double milligramsquaremeters) + { + double value = (double) milligramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareMillimeters(double milligramsquaremillimeters) + { + double value = (double) milligramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from PoundSquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromPoundSquareFeet(double poundsquarefeet) + { + double value = (double) poundsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); + } + /// + /// Get MassMomentOfInertia from PoundSquareInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromPoundSquareInches(double poundsquareinches) + { + double value = (double) poundsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); + } + /// + /// Get MassMomentOfInertia from SlugSquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromSlugSquareFeet(double slugsquarefeet) + { + double value = (double) slugsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); + } + /// + /// Get MassMomentOfInertia from SlugSquareInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromSlugSquareInches(double slugsquareinches) + { + double value = (double) slugsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); + } + /// + /// Get MassMomentOfInertia from TonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareCentimeters(double tonnesquarecentimeters) + { + double value = (double) tonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareDecimeters(double tonnesquaredecimeters) + { + double value = (double) tonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareMeters(double tonnesquaremeters) + { + double value = (double) tonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareMilimeters(double tonnesquaremilimeters) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fromUnit) + { + return new MassMomentOfInertia((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MassMomentOfInertia Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MassMomentOfInertia result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassMomentOfInertiaUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..c3627ad5c0 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Molar energy is the amount of energy stored in 1 mole of a substance. + /// + // 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 MolarEnergy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEnergyUnit? _unit; + + static MolarEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit JoulePerMole. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MolarEnergy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. + /// + public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MolarEnergy; + + /// + /// All units of measurement for the MolarEnergy quantity. + /// + public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. + /// + public static MolarEnergy Zero => new MolarEnergy(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 MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MolarEnergy from JoulesPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEnergy FromJoulesPerMole(double joulespermole) + { + double value = (double) joulespermole; + return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); + } + /// + /// Get MolarEnergy from KilojoulesPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEnergy FromKilojoulesPerMole(double kilojoulespermole) + { + double value = (double) kilojoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); + } + /// + /// Get MolarEnergy from MegajoulesPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEnergy FromMegajoulesPerMole(double megajoulespermole) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) + { + return new MolarEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MolarEnergy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MolarEnergy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarEnergyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..e242f67383 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. + /// + // 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 MolarEntropy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEntropyUnit? _unit; + + static MolarEntropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit JoulePerMoleKelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MolarEntropy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. + /// + public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MolarEntropy; + + /// + /// All units of measurement for the MolarEntropy quantity. + /// + public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. + /// + public static MolarEntropy Zero => new MolarEntropy(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 MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarEntropyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MolarEntropy from JoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEntropy FromJoulesPerMoleKelvin(double joulespermolekelvin) + { + double value = (double) joulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from KilojoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEntropy FromKilojoulesPerMoleKelvin(double kilojoulespermolekelvin) + { + double value = (double) kilojoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from MegajoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEntropy FromMegajoulesPerMoleKelvin(double megajoulespermolekelvin) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) + { + return new MolarEntropy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MolarEntropy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarEntropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MolarEntropy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarEntropyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..6721889a8b --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs @@ -0,0 +1,757 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 MolarMass : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarMassUnit? _unit; + + static MolarMass() + { + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit KilogramPerMole. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public MolarMass() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. + /// + public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MolarMass; + + /// + /// All units of measurement for the MolarMass quantity. + /// + public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. + /// + public static MolarMass Zero => new MolarMass(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 MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarMass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarMass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarMassUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MolarMass from CentigramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromCentigramsPerMole(double centigramspermole) + { + double value = (double) centigramspermole; + return new MolarMass(value, MolarMassUnit.CentigramPerMole); + } + /// + /// Get MolarMass from DecagramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromDecagramsPerMole(double decagramspermole) + { + double value = (double) decagramspermole; + return new MolarMass(value, MolarMassUnit.DecagramPerMole); + } + /// + /// Get MolarMass from DecigramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromDecigramsPerMole(double decigramspermole) + { + double value = (double) decigramspermole; + return new MolarMass(value, MolarMassUnit.DecigramPerMole); + } + /// + /// Get MolarMass from GramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromGramsPerMole(double gramspermole) + { + double value = (double) gramspermole; + return new MolarMass(value, MolarMassUnit.GramPerMole); + } + /// + /// Get MolarMass from HectogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromHectogramsPerMole(double hectogramspermole) + { + double value = (double) hectogramspermole; + return new MolarMass(value, MolarMassUnit.HectogramPerMole); + } + /// + /// Get MolarMass from KilogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromKilogramsPerMole(double kilogramspermole) + { + double value = (double) kilogramspermole; + return new MolarMass(value, MolarMassUnit.KilogramPerMole); + } + /// + /// Get MolarMass from KilopoundsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) + { + double value = (double) kilopoundspermole; + return new MolarMass(value, MolarMassUnit.KilopoundPerMole); + } + /// + /// Get MolarMass from MegapoundsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromMegapoundsPerMole(double megapoundspermole) + { + double value = (double) megapoundspermole; + return new MolarMass(value, MolarMassUnit.MegapoundPerMole); + } + /// + /// Get MolarMass from MicrogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromMicrogramsPerMole(double microgramspermole) + { + double value = (double) microgramspermole; + return new MolarMass(value, MolarMassUnit.MicrogramPerMole); + } + /// + /// Get MolarMass from MilligramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromMilligramsPerMole(double milligramspermole) + { + double value = (double) milligramspermole; + return new MolarMass(value, MolarMassUnit.MilligramPerMole); + } + /// + /// Get MolarMass from NanogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromNanogramsPerMole(double nanogramspermole) + { + double value = (double) nanogramspermole; + return new MolarMass(value, MolarMassUnit.NanogramPerMole); + } + /// + /// Get MolarMass from PoundsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromPoundsPerMole(double poundspermole) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MolarMass From(double value, MolarMassUnit fromUnit) + { + return new MolarMass((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MolarMass Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarMass result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MolarMass result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarMassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarMassUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..9906d6cc14 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,692 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Molar_concentration + /// + // 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 Molarity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarityUnit? _unit; + + static Molarity() + { + BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit MolesPerCubicMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Molarity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Molarity, which is MolesPerCubicMeter. All conversions go via this value. + /// + public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Molarity; + + /// + /// All units of measurement for the Molarity quantity. + /// + public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. + /// + public static Molarity Zero => new Molarity(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 MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Molarity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Molarity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Molarity from CentimolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromCentimolesPerLiter(double centimolesperliter) + { + double value = (double) centimolesperliter; + return new Molarity(value, MolarityUnit.CentimolesPerLiter); + } + /// + /// Get Molarity from DecimolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromDecimolesPerLiter(double decimolesperliter) + { + double value = (double) decimolesperliter; + return new Molarity(value, MolarityUnit.DecimolesPerLiter); + } + /// + /// Get Molarity from MicromolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMicromolesPerLiter(double micromolesperliter) + { + double value = (double) micromolesperliter; + return new Molarity(value, MolarityUnit.MicromolesPerLiter); + } + /// + /// Get Molarity from MillimolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMillimolesPerLiter(double millimolesperliter) + { + double value = (double) millimolesperliter; + return new Molarity(value, MolarityUnit.MillimolesPerLiter); + } + /// + /// Get Molarity from MolesPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMolesPerCubicMeter(double molespercubicmeter) + { + double value = (double) molespercubicmeter; + return new Molarity(value, MolarityUnit.MolesPerCubicMeter); + } + /// + /// Get Molarity from MolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMolesPerLiter(double molesperliter) + { + double value = (double) molesperliter; + return new Molarity(value, MolarityUnit.MolesPerLiter); + } + /// + /// Get Molarity from NanomolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromNanomolesPerLiter(double nanomolesperliter) + { + double value = (double) nanomolesperliter; + return new Molarity(value, MolarityUnit.NanomolesPerLiter); + } + /// + /// Get Molarity from PicomolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromPicomolesPerLiter(double picomolesperliter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Molarity From(double value, MolarityUnit fromUnit) + { + return new Molarity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Molarity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Molarity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Molarity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..0cc81c667b --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) + /// + // 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 Permeability : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermeabilityUnit? _unit; + + static Permeability() + { + BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit HenryPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Permeability() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. + /// + public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Permeability; + + /// + /// All units of measurement for the Permeability quantity. + /// + public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. + /// + public static Permeability Zero => new Permeability(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 PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permeability.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permeability.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permeability in HenriesPerMeter. + /// + public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermeabilityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Permeability from HenriesPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Permeability FromHenriesPerMeter(double henriespermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Permeability From(double value, PermeabilityUnit fromUnit) + { + return new Permeability((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Permeability Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Permeability result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Permeability result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PermeabilityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PermeabilityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..4b244f0049 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Permittivity + /// + // 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 Permittivity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermittivityUnit? _unit; + + static Permittivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit FaradPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Permittivity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. + /// + public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Permittivity; + + /// + /// All units of measurement for the Permittivity quantity. + /// + public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. + /// + public static Permittivity Zero => new Permittivity(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 PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permittivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permittivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permittivity in FaradsPerMeter. + /// + public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermittivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Permittivity from FaradsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Permittivity FromFaradsPerMeter(double faradspermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Permittivity From(double value, PermittivityUnit fromUnit) + { + return new Permittivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Permittivity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Permittivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Permittivity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PermittivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PermittivityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..b63ecedc49 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs @@ -0,0 +1,893 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Power : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerUnit? _unit; + + static Power() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Watt. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Power() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Power, which is Watt. All conversions go via this value. + /// + public static PowerUnit BaseUnit => PowerUnit.Watt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Power; + + /// + /// All units of measurement for the Power quantity. + /// + public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Watt. + /// + public static Power Zero => new Power(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 PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Power.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Power.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PowerUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Power from BoilerHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromBoilerHorsepower(double boilerhorsepower) + { + decimal value = (decimal) boilerhorsepower; + return new Power(value, PowerUnit.BoilerHorsepower); + } + /// + /// Get Power from BritishThermalUnitsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromBritishThermalUnitsPerHour(double britishthermalunitsperhour) + { + decimal value = (decimal) britishthermalunitsperhour; + return new Power(value, PowerUnit.BritishThermalUnitPerHour); + } + /// + /// Get Power from Decawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromDecawatts(double decawatts) + { + decimal value = (decimal) decawatts; + return new Power(value, PowerUnit.Decawatt); + } + /// + /// Get Power from Deciwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromDeciwatts(double deciwatts) + { + decimal value = (decimal) deciwatts; + return new Power(value, PowerUnit.Deciwatt); + } + /// + /// Get Power from ElectricalHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromElectricalHorsepower(double electricalhorsepower) + { + decimal value = (decimal) electricalhorsepower; + return new Power(value, PowerUnit.ElectricalHorsepower); + } + /// + /// Get Power from Femtowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromFemtowatts(double femtowatts) + { + decimal value = (decimal) femtowatts; + return new Power(value, PowerUnit.Femtowatt); + } + /// + /// Get Power from Gigawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromGigawatts(double gigawatts) + { + decimal value = (decimal) gigawatts; + return new Power(value, PowerUnit.Gigawatt); + } + /// + /// Get Power from HydraulicHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromHydraulicHorsepower(double hydraulichorsepower) + { + decimal value = (decimal) hydraulichorsepower; + return new Power(value, PowerUnit.HydraulicHorsepower); + } + /// + /// Get Power from KilobritishThermalUnitsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromKilobritishThermalUnitsPerHour(double kilobritishthermalunitsperhour) + { + decimal value = (decimal) kilobritishthermalunitsperhour; + return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); + } + /// + /// Get Power from Kilowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromKilowatts(double kilowatts) + { + decimal value = (decimal) kilowatts; + return new Power(value, PowerUnit.Kilowatt); + } + /// + /// Get Power from MechanicalHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMechanicalHorsepower(double mechanicalhorsepower) + { + decimal value = (decimal) mechanicalhorsepower; + return new Power(value, PowerUnit.MechanicalHorsepower); + } + /// + /// Get Power from Megawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMegawatts(double megawatts) + { + decimal value = (decimal) megawatts; + return new Power(value, PowerUnit.Megawatt); + } + /// + /// Get Power from MetricHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMetricHorsepower(double metrichorsepower) + { + decimal value = (decimal) metrichorsepower; + return new Power(value, PowerUnit.MetricHorsepower); + } + /// + /// Get Power from Microwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMicrowatts(double microwatts) + { + decimal value = (decimal) microwatts; + return new Power(value, PowerUnit.Microwatt); + } + /// + /// Get Power from Milliwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMilliwatts(double milliwatts) + { + decimal value = (decimal) milliwatts; + return new Power(value, PowerUnit.Milliwatt); + } + /// + /// Get Power from Nanowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromNanowatts(double nanowatts) + { + decimal value = (decimal) nanowatts; + return new Power(value, PowerUnit.Nanowatt); + } + /// + /// Get Power from Petawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromPetawatts(double petawatts) + { + decimal value = (decimal) petawatts; + return new Power(value, PowerUnit.Petawatt); + } + /// + /// Get Power from Picowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromPicowatts(double picowatts) + { + decimal value = (decimal) picowatts; + return new Power(value, PowerUnit.Picowatt); + } + /// + /// Get Power from Terawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromTerawatts(double terawatts) + { + decimal value = (decimal) terawatts; + return new Power(value, PowerUnit.Terawatt); + } + /// + /// Get Power from Watts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromWatts(double watts) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Power From(double value, PowerUnit fromUnit) + { + return new Power((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 Power Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Power Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Power result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Power result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PowerUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..0d0deb8f35 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,1301 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The amount of power in a volume. + /// + // 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 PowerDensity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerDensityUnit? _unit; + + static PowerDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit WattPerCubicMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public PowerDensity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. + /// + public static PowerDensityUnit BaseUnit => PowerDensityUnit.WattPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.PowerDensity; + + /// + /// All units of measurement for the PowerDensity quantity. + /// + public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. + /// + public static PowerDensity Zero => new PowerDensity(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 PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PowerDensity from DecawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerCubicFoot(double decawattspercubicfoot) + { + double value = (double) decawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); + } + /// + /// Get PowerDensity from DecawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerCubicInch(double decawattspercubicinch) + { + double value = (double) decawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); + } + /// + /// Get PowerDensity from DecawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerCubicMeter(double decawattspercubicmeter) + { + double value = (double) decawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); + } + /// + /// Get PowerDensity from DecawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerLiter(double decawattsperliter) + { + double value = (double) decawattsperliter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); + } + /// + /// Get PowerDensity from DeciwattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerCubicFoot(double deciwattspercubicfoot) + { + double value = (double) deciwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); + } + /// + /// Get PowerDensity from DeciwattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerCubicInch(double deciwattspercubicinch) + { + double value = (double) deciwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); + } + /// + /// Get PowerDensity from DeciwattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerCubicMeter(double deciwattspercubicmeter) + { + double value = (double) deciwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); + } + /// + /// Get PowerDensity from DeciwattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerLiter(double deciwattsperliter) + { + double value = (double) deciwattsperliter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); + } + /// + /// Get PowerDensity from GigawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerCubicFoot(double gigawattspercubicfoot) + { + double value = (double) gigawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); + } + /// + /// Get PowerDensity from GigawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerCubicInch(double gigawattspercubicinch) + { + double value = (double) gigawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); + } + /// + /// Get PowerDensity from GigawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerCubicMeter(double gigawattspercubicmeter) + { + double value = (double) gigawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); + } + /// + /// Get PowerDensity from GigawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerLiter(double gigawattsperliter) + { + double value = (double) gigawattsperliter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); + } + /// + /// Get PowerDensity from KilowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerCubicFoot(double kilowattspercubicfoot) + { + double value = (double) kilowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); + } + /// + /// Get PowerDensity from KilowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerCubicInch(double kilowattspercubicinch) + { + double value = (double) kilowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); + } + /// + /// Get PowerDensity from KilowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerCubicMeter(double kilowattspercubicmeter) + { + double value = (double) kilowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); + } + /// + /// Get PowerDensity from KilowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerLiter(double kilowattsperliter) + { + double value = (double) kilowattsperliter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); + } + /// + /// Get PowerDensity from MegawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerCubicFoot(double megawattspercubicfoot) + { + double value = (double) megawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); + } + /// + /// Get PowerDensity from MegawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerCubicInch(double megawattspercubicinch) + { + double value = (double) megawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); + } + /// + /// Get PowerDensity from MegawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerCubicMeter(double megawattspercubicmeter) + { + double value = (double) megawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); + } + /// + /// Get PowerDensity from MegawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerLiter(double megawattsperliter) + { + double value = (double) megawattsperliter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); + } + /// + /// Get PowerDensity from MicrowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerCubicFoot(double microwattspercubicfoot) + { + double value = (double) microwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); + } + /// + /// Get PowerDensity from MicrowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerCubicInch(double microwattspercubicinch) + { + double value = (double) microwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); + } + /// + /// Get PowerDensity from MicrowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerCubicMeter(double microwattspercubicmeter) + { + double value = (double) microwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); + } + /// + /// Get PowerDensity from MicrowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerLiter(double microwattsperliter) + { + double value = (double) microwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); + } + /// + /// Get PowerDensity from MilliwattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerCubicFoot(double milliwattspercubicfoot) + { + double value = (double) milliwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); + } + /// + /// Get PowerDensity from MilliwattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerCubicInch(double milliwattspercubicinch) + { + double value = (double) milliwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); + } + /// + /// Get PowerDensity from MilliwattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerCubicMeter(double milliwattspercubicmeter) + { + double value = (double) milliwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); + } + /// + /// Get PowerDensity from MilliwattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerLiter(double milliwattsperliter) + { + double value = (double) milliwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); + } + /// + /// Get PowerDensity from NanowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerCubicFoot(double nanowattspercubicfoot) + { + double value = (double) nanowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); + } + /// + /// Get PowerDensity from NanowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerCubicInch(double nanowattspercubicinch) + { + double value = (double) nanowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); + } + /// + /// Get PowerDensity from NanowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerCubicMeter(double nanowattspercubicmeter) + { + double value = (double) nanowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); + } + /// + /// Get PowerDensity from NanowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerLiter(double nanowattsperliter) + { + double value = (double) nanowattsperliter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); + } + /// + /// Get PowerDensity from PicowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerCubicFoot(double picowattspercubicfoot) + { + double value = (double) picowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); + } + /// + /// Get PowerDensity from PicowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerCubicInch(double picowattspercubicinch) + { + double value = (double) picowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); + } + /// + /// Get PowerDensity from PicowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerCubicMeter(double picowattspercubicmeter) + { + double value = (double) picowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); + } + /// + /// Get PowerDensity from PicowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerLiter(double picowattsperliter) + { + double value = (double) picowattsperliter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); + } + /// + /// Get PowerDensity from TerawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerCubicFoot(double terawattspercubicfoot) + { + double value = (double) terawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); + } + /// + /// Get PowerDensity from TerawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerCubicInch(double terawattspercubicinch) + { + double value = (double) terawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); + } + /// + /// Get PowerDensity from TerawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerCubicMeter(double terawattspercubicmeter) + { + double value = (double) terawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); + } + /// + /// Get PowerDensity from TerawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerLiter(double terawattsperliter) + { + double value = (double) terawattsperliter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); + } + /// + /// Get PowerDensity from WattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerCubicFoot(double wattspercubicfoot) + { + double value = (double) wattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); + } + /// + /// Get PowerDensity from WattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerCubicInch(double wattspercubicinch) + { + double value = (double) wattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); + } + /// + /// Get PowerDensity from WattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerCubicMeter(double wattspercubicmeter) + { + double value = (double) wattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); + } + /// + /// Get PowerDensity from WattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerLiter(double wattsperliter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static PowerDensity From(double value, PowerDensityUnit fromUnit) + { + return new PowerDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 PowerDensity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PowerDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 PowerDensity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PowerDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PowerDensityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..3f6834c004 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs @@ -0,0 +1,587 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The strength of a signal expressed in decibels (dB) relative to one watt. + /// + // 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 PowerRatio : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerRatioUnit? _unit; + + static PowerRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit DecibelWatt. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public PowerRatio() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. + /// + public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.PowerRatio; + + /// + /// All units of measurement for the PowerRatio quantity. + /// + public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. + /// + public static PowerRatio Zero => new PowerRatio(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 PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PowerRatio in DecibelMilliwatts. + /// + public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + + /// + /// Get PowerRatio in DecibelWatts. + /// + public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerRatioUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PowerRatio from DecibelMilliwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerRatio FromDecibelMilliwatts(double decibelmilliwatts) + { + double value = (double) decibelmilliwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); + } + /// + /// Get PowerRatio from DecibelWatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerRatio FromDecibelWatts(double decibelwatts) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static PowerRatio From(double value, PowerRatioUnit fromUnit) + { + return new PowerRatio((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 PowerRatio Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PowerRatio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 PowerRatio result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PowerRatioUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..33cd62bf6a --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs @@ -0,0 +1,1233 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 Pressure : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureUnit? _unit; + + static Pressure() + { + BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Pascal. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Pressure() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Pressure, which is Pascal. All conversions go via this value. + /// + public static PressureUnit BaseUnit => PressureUnit.Pascal; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Pressure; + + /// + /// All units of measurement for the Pressure quantity. + /// + public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. + /// + public static Pressure Zero => new Pressure(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 PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Pressure.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Pressure.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 DynesPerSquareCentimeter. + /// + public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + + /// + /// 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 Microbars. + /// + public double Microbars => As(PressureUnit.Microbar); + + /// + /// 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 PoundsPerInchSecondSquared. + /// + public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PressureUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Pressure from Atmospheres. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromAtmospheres(double atmospheres) + { + double value = (double) atmospheres; + return new Pressure(value, PressureUnit.Atmosphere); + } + /// + /// Get Pressure from Bars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromBars(double bars) + { + double value = (double) bars; + return new Pressure(value, PressureUnit.Bar); + } + /// + /// Get Pressure from Centibars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromCentibars(double centibars) + { + double value = (double) centibars; + return new Pressure(value, PressureUnit.Centibar); + } + /// + /// Get Pressure from Decapascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromDecapascals(double decapascals) + { + double value = (double) decapascals; + return new Pressure(value, PressureUnit.Decapascal); + } + /// + /// Get Pressure from Decibars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromDecibars(double decibars) + { + double value = (double) decibars; + return new Pressure(value, PressureUnit.Decibar); + } + /// + /// Get Pressure from DynesPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromDynesPerSquareCentimeter(double dynespersquarecentimeter) + { + double value = (double) dynespersquarecentimeter; + return new Pressure(value, PressureUnit.DynePerSquareCentimeter); + } + /// + /// Get Pressure from FeetOfHead. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromFeetOfHead(double feetofhead) + { + double value = (double) feetofhead; + return new Pressure(value, PressureUnit.FootOfHead); + } + /// + /// Get Pressure from Gigapascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromGigapascals(double gigapascals) + { + double value = (double) gigapascals; + return new Pressure(value, PressureUnit.Gigapascal); + } + /// + /// Get Pressure from Hectopascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromHectopascals(double hectopascals) + { + double value = (double) hectopascals; + return new Pressure(value, PressureUnit.Hectopascal); + } + /// + /// Get Pressure from InchesOfMercury. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromInchesOfMercury(double inchesofmercury) + { + double value = (double) inchesofmercury; + return new Pressure(value, PressureUnit.InchOfMercury); + } + /// + /// Get Pressure from Kilobars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilobars(double kilobars) + { + double value = (double) kilobars; + return new Pressure(value, PressureUnit.Kilobar); + } + /// + /// Get Pressure from KilogramsForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilogramsForcePerSquareCentimeter(double kilogramsforcepersquarecentimeter) + { + double value = (double) kilogramsforcepersquarecentimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); + } + /// + /// Get Pressure from KilogramsForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilogramsForcePerSquareMeter(double kilogramsforcepersquaremeter) + { + double value = (double) kilogramsforcepersquaremeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); + } + /// + /// Get Pressure from KilogramsForcePerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilogramsForcePerSquareMillimeter(double kilogramsforcepersquaremillimeter) + { + double value = (double) kilogramsforcepersquaremillimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilonewtonsPerSquareCentimeter(double kilonewtonspersquarecentimeter) + { + double value = (double) kilonewtonspersquarecentimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilonewtonsPerSquareMeter(double kilonewtonspersquaremeter) + { + double value = (double) kilonewtonspersquaremeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilonewtonsPerSquareMillimeter(double kilonewtonspersquaremillimeter) + { + double value = (double) kilonewtonspersquaremillimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); + } + /// + /// Get Pressure from Kilopascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilopascals(double kilopascals) + { + double value = (double) kilopascals; + return new Pressure(value, PressureUnit.Kilopascal); + } + /// + /// Get Pressure from KilopoundsForcePerSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilopoundsForcePerSquareFoot(double kilopoundsforcepersquarefoot) + { + double value = (double) kilopoundsforcepersquarefoot; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); + } + /// + /// Get Pressure from KilopoundsForcePerSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilopoundsForcePerSquareInch(double kilopoundsforcepersquareinch) + { + double value = (double) kilopoundsforcepersquareinch; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); + } + /// + /// Get Pressure from Megabars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMegabars(double megabars) + { + double value = (double) megabars; + return new Pressure(value, PressureUnit.Megabar); + } + /// + /// Get Pressure from MeganewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMeganewtonsPerSquareMeter(double meganewtonspersquaremeter) + { + double value = (double) meganewtonspersquaremeter; + return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); + } + /// + /// Get Pressure from Megapascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMegapascals(double megapascals) + { + double value = (double) megapascals; + return new Pressure(value, PressureUnit.Megapascal); + } + /// + /// Get Pressure from MetersOfHead. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMetersOfHead(double metersofhead) + { + double value = (double) metersofhead; + return new Pressure(value, PressureUnit.MeterOfHead); + } + /// + /// Get Pressure from Microbars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMicrobars(double microbars) + { + double value = (double) microbars; + return new Pressure(value, PressureUnit.Microbar); + } + /// + /// Get Pressure from Micropascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMicropascals(double micropascals) + { + double value = (double) micropascals; + return new Pressure(value, PressureUnit.Micropascal); + } + /// + /// Get Pressure from Millibars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMillibars(double millibars) + { + double value = (double) millibars; + return new Pressure(value, PressureUnit.Millibar); + } + /// + /// Get Pressure from MillimetersOfMercury. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMillimetersOfMercury(double millimetersofmercury) + { + double value = (double) millimetersofmercury; + return new Pressure(value, PressureUnit.MillimeterOfMercury); + } + /// + /// Get Pressure from NewtonsPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromNewtonsPerSquareCentimeter(double newtonspersquarecentimeter) + { + double value = (double) newtonspersquarecentimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); + } + /// + /// Get Pressure from NewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromNewtonsPerSquareMeter(double newtonspersquaremeter) + { + double value = (double) newtonspersquaremeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMeter); + } + /// + /// Get Pressure from NewtonsPerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromNewtonsPerSquareMillimeter(double newtonspersquaremillimeter) + { + double value = (double) newtonspersquaremillimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); + } + /// + /// Get Pressure from Pascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPascals(double pascals) + { + double value = (double) pascals; + return new Pressure(value, PressureUnit.Pascal); + } + /// + /// Get Pressure from PoundsForcePerSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPoundsForcePerSquareFoot(double poundsforcepersquarefoot) + { + double value = (double) poundsforcepersquarefoot; + return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); + } + /// + /// Get Pressure from PoundsForcePerSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPoundsForcePerSquareInch(double poundsforcepersquareinch) + { + double value = (double) poundsforcepersquareinch; + return new Pressure(value, PressureUnit.PoundForcePerSquareInch); + } + /// + /// Get Pressure from PoundsPerInchSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPoundsPerInchSecondSquared(double poundsperinchsecondsquared) + { + double value = (double) poundsperinchsecondsquared; + return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); + } + /// + /// Get Pressure from TechnicalAtmospheres. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTechnicalAtmospheres(double technicalatmospheres) + { + double value = (double) technicalatmospheres; + return new Pressure(value, PressureUnit.TechnicalAtmosphere); + } + /// + /// Get Pressure from TonnesForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTonnesForcePerSquareCentimeter(double tonnesforcepersquarecentimeter) + { + double value = (double) tonnesforcepersquarecentimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTonnesForcePerSquareMeter(double tonnesforcepersquaremeter) + { + double value = (double) tonnesforcepersquaremeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTonnesForcePerSquareMillimeter(double tonnesforcepersquaremillimeter) + { + double value = (double) tonnesforcepersquaremillimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); + } + /// + /// Get Pressure from Torrs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTorrs(double torrs) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Pressure From(double value, PressureUnit fromUnit) + { + return new Pressure((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Pressure Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Pressure result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Pressure result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PressureUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PressureUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.DynePerSquareCentimeter: return _value*1.0e-1; + 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.Microbar: return (_value*1e5) * 1e-6d; + 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.PoundPerInchSecondSquared: return _value*1.785796732283465e1; + 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.DynePerSquareCentimeter: return baseUnitValue/1.0e-1; + 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.Microbar: return (baseUnitValue/1e5) / 1e-6d; + 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.PoundPerInchSecondSquared: return baseUnitValue/1.785796732283465e1; + 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..d9d49c8ca4 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs @@ -0,0 +1,621 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 PressureChangeRate : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureChangeRateUnit? _unit; + + static PressureChangeRate() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit PascalPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public PressureChangeRate() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. + /// + public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.PressureChangeRate; + + /// + /// All units of measurement for the PressureChangeRate quantity. + /// + public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. + /// + public static PressureChangeRate Zero => new PressureChangeRate(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 PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PressureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PressureChangeRate from AtmospheresPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromAtmospheresPerSecond(double atmospherespersecond) + { + double value = (double) atmospherespersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); + } + /// + /// Get PressureChangeRate from KilopascalsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromKilopascalsPerSecond(double kilopascalspersecond) + { + double value = (double) kilopascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); + } + /// + /// Get PressureChangeRate from MegapascalsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromMegapascalsPerSecond(double megapascalspersecond) + { + double value = (double) megapascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); + } + /// + /// Get PressureChangeRate from PascalsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromPascalsPerSecond(double pascalspersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static PressureChangeRate From(double value, PressureChangeRateUnit fromUnit) + { + return new PressureChangeRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 PressureChangeRate Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PressureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 PressureChangeRate result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PressureChangeRateUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..28e40e140f --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs @@ -0,0 +1,655 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 Ratio : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RatioUnit? _unit; + + static Ratio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit DecimalFraction. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Ratio() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. + /// + public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Ratio; + + /// + /// All units of measurement for the Ratio quantity. + /// + public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// + public static Ratio Zero => new Ratio(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 RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Ratio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Ratio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RatioUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(RatioUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Ratio from DecimalFractions. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromDecimalFractions(double decimalfractions) + { + double value = (double) decimalfractions; + return new Ratio(value, RatioUnit.DecimalFraction); + } + /// + /// Get Ratio from PartsPerBillion. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerBillion(double partsperbillion) + { + double value = (double) partsperbillion; + return new Ratio(value, RatioUnit.PartPerBillion); + } + /// + /// Get Ratio from PartsPerMillion. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerMillion(double partspermillion) + { + double value = (double) partspermillion; + return new Ratio(value, RatioUnit.PartPerMillion); + } + /// + /// Get Ratio from PartsPerThousand. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerThousand(double partsperthousand) + { + double value = (double) partsperthousand; + return new Ratio(value, RatioUnit.PartPerThousand); + } + /// + /// Get Ratio from PartsPerTrillion. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerTrillion(double partspertrillion) + { + double value = (double) partspertrillion; + return new Ratio(value, RatioUnit.PartPerTrillion); + } + /// + /// Get Ratio from Percent. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPercent(double percent) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Ratio From(double value, RatioUnit fromUnit) + { + return new Ratio((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Ratio Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Ratio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Ratio result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RatioUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..893f7b32dc --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ReactiveEnergy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactiveEnergyUnit? _unit; + + static ReactiveEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit VoltampereReactiveHour. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ReactiveEnergy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. + /// + public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ReactiveEnergy; + + /// + /// All units of measurement for the ReactiveEnergy quantity. + /// + public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. + /// + public static ReactiveEnergy Zero => new ReactiveEnergy(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 ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactiveEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ReactiveEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ReactiveEnergy from KilovoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactiveEnergy FromKilovoltampereReactiveHours(double kilovoltamperereactivehours) + { + double value = (double) kilovoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from MegavoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactiveEnergy FromMegavoltampereReactiveHours(double megavoltamperereactivehours) + { + double value = (double) megavoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from VoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactiveEnergy FromVoltampereReactiveHours(double voltamperereactivehours) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) + { + return new ReactiveEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ReactiveEnergy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ReactiveEnergy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ReactiveEnergyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..6cdb0d0f9b --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs @@ -0,0 +1,621 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 ReactivePower : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactivePowerUnit? _unit; + + static ReactivePower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit VoltampereReactive. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ReactivePower() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. + /// + public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ReactivePower; + + /// + /// All units of measurement for the ReactivePower quantity. + /// + public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. + /// + public static ReactivePower Zero => new ReactivePower(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 ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactivePower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactivePower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ReactivePowerUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ReactivePower from GigavoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromGigavoltamperesReactive(double gigavoltamperesreactive) + { + double value = (double) gigavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); + } + /// + /// Get ReactivePower from KilovoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromKilovoltamperesReactive(double kilovoltamperesreactive) + { + double value = (double) kilovoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); + } + /// + /// Get ReactivePower from MegavoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromMegavoltamperesReactive(double megavoltamperesreactive) + { + double value = (double) megavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); + } + /// + /// Get ReactivePower from VoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromVoltamperesReactive(double voltamperesreactive) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ReactivePower From(double value, ReactivePowerUnit fromUnit) + { + return new ReactivePower((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ReactivePower Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ReactivePower result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ReactivePower result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ReactivePowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ReactivePowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ReactivePowerUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..8b9c1aea4c --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Angular acceleration is the rate of change of rotational speed. + /// + // 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 RotationalAcceleration : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalAccelerationUnit? _unit; + + static RotationalAcceleration() + { + BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit RadianPerSecondSquared. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public RotationalAcceleration() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. + /// + public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalAcceleration; + + /// + /// All units of measurement for the RotationalAcceleration quantity. + /// + public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. + /// + public static RotationalAcceleration Zero => new RotationalAcceleration(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 RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalAcceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalAccelerationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalAcceleration from DegreesPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalAcceleration FromDegreesPerSecondSquared(double degreespersecondsquared) + { + double value = (double) degreespersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); + } + /// + /// Get RotationalAcceleration from RadiansPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalAcceleration FromRadiansPerSecondSquared(double radianspersecondsquared) + { + double value = (double) radianspersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); + } + /// + /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double revolutionsperminutepersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalAcceleration From(double value, RotationalAccelerationUnit fromUnit) + { + return new RotationalAcceleration((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalAcceleration Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalAcceleration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalAcceleration result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalAccelerationUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..da8191f564 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs @@ -0,0 +1,774 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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"). + /// + // 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 RotationalSpeed : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalSpeedUnit? _unit; + + static RotationalSpeed() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit RadianPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public RotationalSpeed() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. + /// + public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalSpeed; + + /// + /// All units of measurement for the RotationalSpeed quantity. + /// + public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. + /// + public static RotationalSpeed Zero => new RotationalSpeed(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 RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalSpeed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalSpeedUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalSpeed from CentiradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromCentiradiansPerSecond(double centiradianspersecond) + { + double value = (double) centiradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); + } + /// + /// Get RotationalSpeed from DeciradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromDeciradiansPerSecond(double deciradianspersecond) + { + double value = (double) deciradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); + } + /// + /// Get RotationalSpeed from DegreesPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromDegreesPerMinute(double degreesperminute) + { + double value = (double) degreesperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); + } + /// + /// Get RotationalSpeed from DegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromDegreesPerSecond(double degreespersecond) + { + double value = (double) degreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); + } + /// + /// Get RotationalSpeed from MicrodegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMicrodegreesPerSecond(double microdegreespersecond) + { + double value = (double) microdegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); + } + /// + /// Get RotationalSpeed from MicroradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMicroradiansPerSecond(double microradianspersecond) + { + double value = (double) microradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); + } + /// + /// Get RotationalSpeed from MillidegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMillidegreesPerSecond(double millidegreespersecond) + { + double value = (double) millidegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); + } + /// + /// Get RotationalSpeed from MilliradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMilliradiansPerSecond(double milliradianspersecond) + { + double value = (double) milliradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); + } + /// + /// Get RotationalSpeed from NanodegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromNanodegreesPerSecond(double nanodegreespersecond) + { + double value = (double) nanodegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); + } + /// + /// Get RotationalSpeed from NanoradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromNanoradiansPerSecond(double nanoradianspersecond) + { + double value = (double) nanoradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); + } + /// + /// Get RotationalSpeed from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromRadiansPerSecond(double radianspersecond) + { + double value = (double) radianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); + } + /// + /// Get RotationalSpeed from RevolutionsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromRevolutionsPerMinute(double revolutionsperminute) + { + double value = (double) revolutionsperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); + } + /// + /// Get RotationalSpeed from RevolutionsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromRevolutionsPerSecond(double revolutionspersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) + { + return new RotationalSpeed((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalSpeed Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalSpeed result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalSpeedUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..b335fe2018 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness + /// + // 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 RotationalStiffness : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessUnit? _unit; + + static RotationalStiffness() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerRadian. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public RotationalStiffness() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. + /// + public static RotationalStiffnessUnit BaseUnit => RotationalStiffnessUnit.NewtonMeterPerRadian; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalStiffness; + + /// + /// All units of measurement for the RotationalStiffness quantity. + /// + public static RotationalStiffnessUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. + /// + public static RotationalStiffness Zero => new RotationalStiffness(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 RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffness.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalStiffnessUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalStiffness from KilonewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffness FromKilonewtonMetersPerRadian(double kilonewtonmetersperradian) + { + double value = (double) kilonewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from MeganewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffness FromMeganewtonMetersPerRadian(double meganewtonmetersperradian) + { + double value = (double) meganewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from NewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffness FromNewtonMetersPerRadian(double newtonmetersperradian) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalStiffness From(double value, RotationalStiffnessUnit fromUnit) + { + return new RotationalStiffness((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalStiffness Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalStiffness result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalStiffness result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalStiffnessUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalStiffnessUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..e537623e26 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs @@ -0,0 +1,604 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness + /// + // 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 RotationalStiffnessPerLength : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessPerLengthUnit? _unit; + + static RotationalStiffnessPerLength() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public RotationalStiffnessPerLength() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. + /// + public static RotationalStiffnessPerLengthUnit BaseUnit => RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalStiffnessPerLength; + + /// + /// All units of measurement for the RotationalStiffnessPerLength quantity. + /// + public static RotationalStiffnessPerLengthUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. + /// + public static RotationalStiffnessPerLength Zero => new RotationalStiffnessPerLength(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 RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffnessPerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalStiffnessPerLength from KilonewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(double kilonewtonmetersperradianpermeter) + { + double value = (double) kilonewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from MeganewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(double meganewtonmetersperradianpermeter) + { + double value = (double) meganewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from NewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(double newtonmetersperradianpermeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalStiffnessPerLength From(double value, RotationalStiffnessPerLengthUnit fromUnit) + { + return new RotationalStiffnessPerLength((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalStiffnessPerLength Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalStiffnessPerLength result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalStiffnessPerLength result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalStiffnessPerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalStiffnessPerLengthUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..a2734f7231 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs @@ -0,0 +1,573 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Solid_angle + /// + // 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 SolidAngle : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SolidAngleUnit? _unit; + + static SolidAngle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit Steradian. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public SolidAngle() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. + /// + public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SolidAngle; + + /// + /// All units of measurement for the SolidAngle quantity. + /// + public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. + /// + public static SolidAngle Zero => new SolidAngle(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 SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SolidAngle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SolidAngle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SolidAngle in Steradians. + /// + public double Steradians => As(SolidAngleUnit.Steradian); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SolidAngleUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SolidAngle from Steradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SolidAngle FromSteradians(double steradians) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static SolidAngle From(double value, SolidAngleUnit fromUnit) + { + return new SolidAngle((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SolidAngle Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SolidAngle result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SolidAngle result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SolidAngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SolidAngleUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..c526b4488b --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,692 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The SpecificEnergy + /// + /// + /// https://en.wikipedia.org/wiki/Specific_energy + /// + // 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 SpecificEnergy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificEnergyUnit? _unit; + + static SpecificEnergy() + { + BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit JoulePerKilogram. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public SpecificEnergy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. + /// + public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificEnergy; + + /// + /// All units of measurement for the SpecificEnergy quantity. + /// + public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. + /// + public static SpecificEnergy Zero => new SpecificEnergy(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 SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificEnergy from CaloriesPerGram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) + { + double value = (double) caloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); + } + /// + /// Get SpecificEnergy from JoulesPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) + { + double value = (double) joulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilocaloriesPerGram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) + { + double value = (double) kilocaloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); + } + /// + /// Get SpecificEnergy from KilojoulesPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) + { + double value = (double) kilojoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilowattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) + { + double value = (double) kilowatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); + } + /// + /// Get SpecificEnergy from MegajoulesPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) + { + double value = (double) megajoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); + } + /// + /// Get SpecificEnergy from MegawattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) + { + double value = (double) megawatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); + } + /// + /// Get SpecificEnergy from WattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) + { + return new SpecificEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificEnergy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificEnergy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificEnergyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..ebc52aea2a --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs @@ -0,0 +1,689 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 SpecificEntropy : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificEntropyUnit? _unit; + + static SpecificEntropy() + { + BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit JoulePerKilogramKelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public SpecificEntropy() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. + /// + public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificEntropy; + + /// + /// All units of measurement for the SpecificEntropy quantity. + /// + public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. + /// + public static SpecificEntropy Zero => new SpecificEntropy(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 SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificEntropyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificEntropy from CaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromCaloriesPerGramKelvin(double caloriespergramkelvin) + { + double value = (double) caloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double joulesperkilogramdegreecelsius) + { + double value = (double) joulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from JoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromJoulesPerKilogramKelvin(double joulesperkilogramkelvin) + { + double value = (double) joulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from KilocaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromKilocaloriesPerGramKelvin(double kilocaloriespergramkelvin) + { + double value = (double) kilocaloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double kilojoulesperkilogramdegreecelsius) + { + double value = (double) kilojoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double kilojoulesperkilogramkelvin) + { + double value = (double) kilojoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double megajoulesperkilogramdegreecelsius) + { + double value = (double) megajoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double megajoulesperkilogramkelvin) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) + { + return new SpecificEntropy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificEntropy Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificEntropy result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificEntropyUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..dab2338cc9 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs @@ -0,0 +1,587 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 SpecificVolume : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificVolumeUnit? _unit; + + static SpecificVolume() + { + BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit CubicMeterPerKilogram. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public SpecificVolume() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. + /// + public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificVolume; + + /// + /// All units of measurement for the SpecificVolume quantity. + /// + public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. + /// + public static SpecificVolume Zero => new SpecificVolume(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 SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificVolume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificVolume in CubicFeetPerPound. + /// + public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + + /// + /// Get SpecificVolume in CubicMetersPerKilogram. + /// + public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificVolumeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificVolume from CubicFeetPerPound. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificVolume FromCubicFeetPerPound(double cubicfeetperpound) + { + double value = (double) cubicfeetperpound; + return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); + } + /// + /// Get SpecificVolume from CubicMetersPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificVolume FromCubicMetersPerKilogram(double cubicmetersperkilogram) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) + { + return new SpecificVolume((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificVolume Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificVolume result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificVolume result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificVolumeUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..e4fa1ed151 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs @@ -0,0 +1,845 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. + /// + /// + /// http://en.wikipedia.org/wiki/Specificweight + /// + // 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 SpecificWeight : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificWeightUnit? _unit; + + static SpecificWeight() + { + BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonPerCubicMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public SpecificWeight() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. + /// + public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificWeight; + + /// + /// All units of measurement for the SpecificWeight quantity. + /// + public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. + /// + public static SpecificWeight Zero => new SpecificWeight(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 SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificWeight.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificWeightUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double kilogramsforcepercubiccentimeter) + { + double value = (double) kilogramsforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from KilogramsForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilogramsForcePerCubicMeter(double kilogramsforcepercubicmeter) + { + double value = (double) kilogramsforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); + } + /// + /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double kilogramsforcepercubicmillimeter) + { + double value = (double) kilogramsforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double kilonewtonspercubiccentimeter) + { + double value = (double) kilonewtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilonewtonsPerCubicMeter(double kilonewtonspercubicmeter) + { + double value = (double) kilonewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double kilonewtonspercubicmillimeter) + { + double value = (double) kilonewtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from KilopoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilopoundsForcePerCubicFoot(double kilopoundsforcepercubicfoot) + { + double value = (double) kilopoundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from KilopoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilopoundsForcePerCubicInch(double kilopoundsforcepercubicinch) + { + double value = (double) kilopoundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); + } + /// + /// Get SpecificWeight from MeganewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromMeganewtonsPerCubicMeter(double meganewtonspercubicmeter) + { + double value = (double) meganewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromNewtonsPerCubicCentimeter(double newtonspercubiccentimeter) + { + double value = (double) newtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromNewtonsPerCubicMeter(double newtonspercubicmeter) + { + double value = (double) newtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromNewtonsPerCubicMillimeter(double newtonspercubicmillimeter) + { + double value = (double) newtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromPoundsForcePerCubicFoot(double poundsforcepercubicfoot) + { + double value = (double) poundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromPoundsForcePerCubicInch(double poundsforcepercubicinch) + { + double value = (double) poundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromTonnesForcePerCubicCentimeter(double tonnesforcepercubiccentimeter) + { + double value = (double) tonnesforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromTonnesForcePerCubicMeter(double tonnesforcepercubicmeter) + { + double value = (double) tonnesforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromTonnesForcePerCubicMillimeter(double tonnesforcepercubicmillimeter) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) + { + return new SpecificWeight((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificWeight Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificWeight result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificWeight result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificWeightUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificWeightUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..2580e57b88 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs @@ -0,0 +1,1097 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Speed : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpeedUnit? _unit; + + static Speed() + { + BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit MeterPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Speed() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. + /// + public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Speed; + + /// + /// All units of measurement for the Speed quantity. + /// + public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. + /// + public static Speed Zero => new Speed(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 SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Speed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Speed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpeedUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Speed from CentimetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromCentimetersPerHour(double centimetersperhour) + { + double value = (double) centimetersperhour; + return new Speed(value, SpeedUnit.CentimeterPerHour); + } + /// + /// Get Speed from CentimetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromCentimetersPerMinutes(double centimetersperminutes) + { + double value = (double) centimetersperminutes; + return new Speed(value, SpeedUnit.CentimeterPerMinute); + } + /// + /// Get Speed from CentimetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromCentimetersPerSecond(double centimeterspersecond) + { + double value = (double) centimeterspersecond; + return new Speed(value, SpeedUnit.CentimeterPerSecond); + } + /// + /// Get Speed from DecimetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromDecimetersPerMinutes(double decimetersperminutes) + { + double value = (double) decimetersperminutes; + return new Speed(value, SpeedUnit.DecimeterPerMinute); + } + /// + /// Get Speed from DecimetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromDecimetersPerSecond(double decimeterspersecond) + { + double value = (double) decimeterspersecond; + return new Speed(value, SpeedUnit.DecimeterPerSecond); + } + /// + /// Get Speed from FeetPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromFeetPerHour(double feetperhour) + { + double value = (double) feetperhour; + return new Speed(value, SpeedUnit.FootPerHour); + } + /// + /// Get Speed from FeetPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromFeetPerMinute(double feetperminute) + { + double value = (double) feetperminute; + return new Speed(value, SpeedUnit.FootPerMinute); + } + /// + /// Get Speed from FeetPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromFeetPerSecond(double feetpersecond) + { + double value = (double) feetpersecond; + return new Speed(value, SpeedUnit.FootPerSecond); + } + /// + /// Get Speed from InchesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromInchesPerHour(double inchesperhour) + { + double value = (double) inchesperhour; + return new Speed(value, SpeedUnit.InchPerHour); + } + /// + /// Get Speed from InchesPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromInchesPerMinute(double inchesperminute) + { + double value = (double) inchesperminute; + return new Speed(value, SpeedUnit.InchPerMinute); + } + /// + /// Get Speed from InchesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromInchesPerSecond(double inchespersecond) + { + double value = (double) inchespersecond; + return new Speed(value, SpeedUnit.InchPerSecond); + } + /// + /// Get Speed from KilometersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKilometersPerHour(double kilometersperhour) + { + double value = (double) kilometersperhour; + return new Speed(value, SpeedUnit.KilometerPerHour); + } + /// + /// Get Speed from KilometersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKilometersPerMinutes(double kilometersperminutes) + { + double value = (double) kilometersperminutes; + return new Speed(value, SpeedUnit.KilometerPerMinute); + } + /// + /// Get Speed from KilometersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKilometersPerSecond(double kilometerspersecond) + { + double value = (double) kilometerspersecond; + return new Speed(value, SpeedUnit.KilometerPerSecond); + } + /// + /// Get Speed from Knots. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKnots(double knots) + { + double value = (double) knots; + return new Speed(value, SpeedUnit.Knot); + } + /// + /// Get Speed from MetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMetersPerHour(double metersperhour) + { + double value = (double) metersperhour; + return new Speed(value, SpeedUnit.MeterPerHour); + } + /// + /// Get Speed from MetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMetersPerMinutes(double metersperminutes) + { + double value = (double) metersperminutes; + return new Speed(value, SpeedUnit.MeterPerMinute); + } + /// + /// Get Speed from MetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMetersPerSecond(double meterspersecond) + { + double value = (double) meterspersecond; + return new Speed(value, SpeedUnit.MeterPerSecond); + } + /// + /// Get Speed from MicrometersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMicrometersPerMinutes(double micrometersperminutes) + { + double value = (double) micrometersperminutes; + return new Speed(value, SpeedUnit.MicrometerPerMinute); + } + /// + /// Get Speed from MicrometersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMicrometersPerSecond(double micrometerspersecond) + { + double value = (double) micrometerspersecond; + return new Speed(value, SpeedUnit.MicrometerPerSecond); + } + /// + /// Get Speed from MilesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMilesPerHour(double milesperhour) + { + double value = (double) milesperhour; + return new Speed(value, SpeedUnit.MilePerHour); + } + /// + /// Get Speed from MillimetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMillimetersPerHour(double millimetersperhour) + { + double value = (double) millimetersperhour; + return new Speed(value, SpeedUnit.MillimeterPerHour); + } + /// + /// Get Speed from MillimetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMillimetersPerMinutes(double millimetersperminutes) + { + double value = (double) millimetersperminutes; + return new Speed(value, SpeedUnit.MillimeterPerMinute); + } + /// + /// Get Speed from MillimetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMillimetersPerSecond(double millimeterspersecond) + { + double value = (double) millimeterspersecond; + return new Speed(value, SpeedUnit.MillimeterPerSecond); + } + /// + /// Get Speed from NanometersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromNanometersPerMinutes(double nanometersperminutes) + { + double value = (double) nanometersperminutes; + return new Speed(value, SpeedUnit.NanometerPerMinute); + } + /// + /// Get Speed from NanometersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromNanometersPerSecond(double nanometerspersecond) + { + double value = (double) nanometerspersecond; + return new Speed(value, SpeedUnit.NanometerPerSecond); + } + /// + /// Get Speed from UsSurveyFeetPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromUsSurveyFeetPerHour(double ussurveyfeetperhour) + { + double value = (double) ussurveyfeetperhour; + return new Speed(value, SpeedUnit.UsSurveyFootPerHour); + } + /// + /// Get Speed from UsSurveyFeetPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromUsSurveyFeetPerMinute(double ussurveyfeetperminute) + { + double value = (double) ussurveyfeetperminute; + return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); + } + /// + /// Get Speed from UsSurveyFeetPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromUsSurveyFeetPerSecond(double ussurveyfeetpersecond) + { + double value = (double) ussurveyfeetpersecond; + return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); + } + /// + /// Get Speed from YardsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromYardsPerHour(double yardsperhour) + { + double value = (double) yardsperhour; + return new Speed(value, SpeedUnit.YardPerHour); + } + /// + /// Get Speed from YardsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromYardsPerMinute(double yardsperminute) + { + double value = (double) yardsperminute; + return new Speed(value, SpeedUnit.YardPerMinute); + } + /// + /// Get Speed from YardsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromYardsPerSecond(double yardspersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Speed From(double value, SpeedUnit fromUnit) + { + return new Speed((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Speed Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Speed result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Speed result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpeedUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..d938c21971 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs @@ -0,0 +1,689 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Temperature : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureUnit? _unit; + + static Temperature() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit Kelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Temperature() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Temperature, which is Kelvin. All conversions go via this value. + /// + public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Temperature; + + /// + /// All units of measurement for the Temperature quantity. + /// + public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static Temperature Zero => new Temperature(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 TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Temperature.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Temperature.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Temperature from DegreesCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesCelsius(double degreescelsius) + { + double value = (double) degreescelsius; + return new Temperature(value, TemperatureUnit.DegreeCelsius); + } + /// + /// Get Temperature from DegreesDelisle. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesDelisle(double degreesdelisle) + { + double value = (double) degreesdelisle; + return new Temperature(value, TemperatureUnit.DegreeDelisle); + } + /// + /// Get Temperature from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesFahrenheit(double degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new Temperature(value, TemperatureUnit.DegreeFahrenheit); + } + /// + /// Get Temperature from DegreesNewton. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesNewton(double degreesnewton) + { + double value = (double) degreesnewton; + return new Temperature(value, TemperatureUnit.DegreeNewton); + } + /// + /// Get Temperature from DegreesRankine. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesRankine(double degreesrankine) + { + double value = (double) degreesrankine; + return new Temperature(value, TemperatureUnit.DegreeRankine); + } + /// + /// Get Temperature from DegreesReaumur. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesReaumur(double degreesreaumur) + { + double value = (double) degreesreaumur; + return new Temperature(value, TemperatureUnit.DegreeReaumur); + } + /// + /// Get Temperature from DegreesRoemer. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesRoemer(double degreesroemer) + { + double value = (double) degreesroemer; + return new Temperature(value, TemperatureUnit.DegreeRoemer); + } + /// + /// Get Temperature from Kelvins. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromKelvins(double kelvins) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Temperature From(double value, TemperatureUnit fromUnit) + { + return new Temperature((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Temperature Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Temperature result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Temperature result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TemperatureUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..e27815d279 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs @@ -0,0 +1,723 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + // 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 TemperatureChangeRate : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureChangeRateUnit? _unit; + + static TemperatureChangeRate() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public TemperatureChangeRate() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. + /// + public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.TemperatureChangeRate; + + /// + /// All units of measurement for the TemperatureChangeRate quantity. + /// + public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. + /// + public static TemperatureChangeRate Zero => new TemperatureChangeRate(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 TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double centidegreescelsiuspersecond) + { + double value = (double) centidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double decadegreescelsiuspersecond) + { + double value = (double) decadegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double decidegreescelsiuspersecond) + { + double value = (double) decidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double degreescelsiusperminute) + { + double value = (double) degreescelsiusperminute; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + } + /// + /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double degreescelsiuspersecond) + { + double value = (double) degreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double hectodegreescelsiuspersecond) + { + double value = (double) hectodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double kilodegreescelsiuspersecond) + { + double value = (double) kilodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double microdegreescelsiuspersecond) + { + double value = (double) microdegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double millidegreescelsiuspersecond) + { + double value = (double) millidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double nanodegreescelsiuspersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit fromUnit) + { + return new TemperatureChangeRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 TemperatureChangeRate Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 TemperatureChangeRate result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TemperatureChangeRateUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..85bef47194 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs @@ -0,0 +1,689 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Difference between two temperatures. The conversions are different than for Temperature. + /// + // 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 TemperatureDelta : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureDeltaUnit? _unit; + + static TemperatureDelta() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit Kelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public TemperatureDelta() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. + /// + public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.TemperatureDelta; + + /// + /// All units of measurement for the TemperatureDelta quantity. + /// + public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static TemperatureDelta Zero => new TemperatureDelta(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 TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureDelta.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureDeltaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get TemperatureDelta from DegreesCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesCelsius(double degreescelsius) + { + double value = (double) degreescelsius; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); + } + /// + /// Get TemperatureDelta from DegreesDelisle. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesDelisle(double degreesdelisle) + { + double value = (double) degreesdelisle; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); + } + /// + /// Get TemperatureDelta from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesFahrenheit(double degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); + } + /// + /// Get TemperatureDelta from DegreesNewton. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesNewton(double degreesnewton) + { + double value = (double) degreesnewton; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); + } + /// + /// Get TemperatureDelta from DegreesRankine. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesRankine(double degreesrankine) + { + double value = (double) degreesrankine; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); + } + /// + /// Get TemperatureDelta from DegreesReaumur. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesReaumur(double degreesreaumur) + { + double value = (double) degreesreaumur; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); + } + /// + /// Get TemperatureDelta from DegreesRoemer. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesRoemer(double degreesroemer) + { + double value = (double) degreesroemer; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); + } + /// + /// Get TemperatureDelta from Kelvins. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromKelvins(double kelvins) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) + { + return new TemperatureDelta((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 TemperatureDelta Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out TemperatureDelta result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 TemperatureDelta result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TemperatureDeltaUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..1cfdd85421 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs @@ -0,0 +1,590 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Thermal conductivity is the property of a material to conduct heat. + /// + /// + /// https://en.wikipedia.org/wiki/Thermal_Conductivity + /// + // 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 ThermalConductivity : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalConductivityUnit? _unit; + + static ThermalConductivity() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit WattPerMeterKelvin. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ThermalConductivity() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. + /// + public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ThermalConductivity; + + /// + /// All units of measurement for the ThermalConductivity quantity. + /// + public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. + /// + public static ThermalConductivity Zero => new ThermalConductivity(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 ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ThermalConductivity in BtusPerHourFootFahrenheit. + /// + public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + + /// + /// Get ThermalConductivity in WattsPerMeterKelvin. + /// + public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalConductivity from BtusPerHourFootFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalConductivity FromBtusPerHourFootFahrenheit(double btusperhourfootfahrenheit) + { + double value = (double) btusperhourfootfahrenheit; + return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); + } + /// + /// Get ThermalConductivity from WattsPerMeterKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalConductivity FromWattsPerMeterKelvin(double wattspermeterkelvin) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ThermalConductivity From(double value, ThermalConductivityUnit fromUnit) + { + return new ThermalConductivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ThermalConductivity Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ThermalConductivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ThermalConductivity result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ThermalConductivityUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..c4e9a2caf2 --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs @@ -0,0 +1,638 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. + /// + // 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 ThermalResistance : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalResistanceUnit? _unit; + + static ThermalResistance() + { + BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public ThermalResistance() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. + /// + public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ThermalResistance; + + /// + /// All units of measurement for the ThermalResistance quantity. + /// + public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. + /// + public static ThermalResistance Zero => new ThermalResistance(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 ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalResistanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(double hoursquarefeetdegreesfahrenheitperbtu) + { + double value = (double) hoursquarefeetdegreesfahrenheitperbtu; + return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + } + /// + /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double squarecentimeterhourdegreescelsiusperkilocalorie) + { + double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + } + /// + /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(double squarecentimeterkelvinsperwatt) + { + double value = (double) squarecentimeterkelvinsperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + } + /// + /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(double squaremeterdegreescelsiusperwatt) + { + double value = (double) squaremeterdegreescelsiusperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + } + /// + /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(double squaremeterkelvinsperkilowatt) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ThermalResistance From(double value, ThermalResistanceUnit fromUnit) + { + return new ThermalResistance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ThermalResistance Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ThermalResistance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ThermalResistance result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ThermalResistanceUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..5f5be9e35a --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs @@ -0,0 +1,910 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Torque : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TorqueUnit? _unit; + + static Torque() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit NewtonMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Torque() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. + /// + public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Torque; + + /// + /// All units of measurement for the Torque quantity. + /// + public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. + /// + public static Torque Zero => new Torque(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 TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Torque.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Torque.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TorqueUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Torque from KilogramForceCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilogramForceCentimeters(double kilogramforcecentimeters) + { + double value = (double) kilogramforcecentimeters; + return new Torque(value, TorqueUnit.KilogramForceCentimeter); + } + /// + /// Get Torque from KilogramForceMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilogramForceMeters(double kilogramforcemeters) + { + double value = (double) kilogramforcemeters; + return new Torque(value, TorqueUnit.KilogramForceMeter); + } + /// + /// Get Torque from KilogramForceMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilogramForceMillimeters(double kilogramforcemillimeters) + { + double value = (double) kilogramforcemillimeters; + return new Torque(value, TorqueUnit.KilogramForceMillimeter); + } + /// + /// Get Torque from KilonewtonCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilonewtonCentimeters(double kilonewtoncentimeters) + { + double value = (double) kilonewtoncentimeters; + return new Torque(value, TorqueUnit.KilonewtonCentimeter); + } + /// + /// Get Torque from KilonewtonMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilonewtonMeters(double kilonewtonmeters) + { + double value = (double) kilonewtonmeters; + return new Torque(value, TorqueUnit.KilonewtonMeter); + } + /// + /// Get Torque from KilonewtonMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilonewtonMillimeters(double kilonewtonmillimeters) + { + double value = (double) kilonewtonmillimeters; + return new Torque(value, TorqueUnit.KilonewtonMillimeter); + } + /// + /// Get Torque from KilopoundForceFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilopoundForceFeet(double kilopoundforcefeet) + { + double value = (double) kilopoundforcefeet; + return new Torque(value, TorqueUnit.KilopoundForceFoot); + } + /// + /// Get Torque from KilopoundForceInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilopoundForceInches(double kilopoundforceinches) + { + double value = (double) kilopoundforceinches; + return new Torque(value, TorqueUnit.KilopoundForceInch); + } + /// + /// Get Torque from MeganewtonCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMeganewtonCentimeters(double meganewtoncentimeters) + { + double value = (double) meganewtoncentimeters; + return new Torque(value, TorqueUnit.MeganewtonCentimeter); + } + /// + /// Get Torque from MeganewtonMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMeganewtonMeters(double meganewtonmeters) + { + double value = (double) meganewtonmeters; + return new Torque(value, TorqueUnit.MeganewtonMeter); + } + /// + /// Get Torque from MeganewtonMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMeganewtonMillimeters(double meganewtonmillimeters) + { + double value = (double) meganewtonmillimeters; + return new Torque(value, TorqueUnit.MeganewtonMillimeter); + } + /// + /// Get Torque from MegapoundForceFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMegapoundForceFeet(double megapoundforcefeet) + { + double value = (double) megapoundforcefeet; + return new Torque(value, TorqueUnit.MegapoundForceFoot); + } + /// + /// Get Torque from MegapoundForceInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMegapoundForceInches(double megapoundforceinches) + { + double value = (double) megapoundforceinches; + return new Torque(value, TorqueUnit.MegapoundForceInch); + } + /// + /// Get Torque from NewtonCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromNewtonCentimeters(double newtoncentimeters) + { + double value = (double) newtoncentimeters; + return new Torque(value, TorqueUnit.NewtonCentimeter); + } + /// + /// Get Torque from NewtonMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromNewtonMeters(double newtonmeters) + { + double value = (double) newtonmeters; + return new Torque(value, TorqueUnit.NewtonMeter); + } + /// + /// Get Torque from NewtonMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromNewtonMillimeters(double newtonmillimeters) + { + double value = (double) newtonmillimeters; + return new Torque(value, TorqueUnit.NewtonMillimeter); + } + /// + /// Get Torque from PoundForceFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromPoundForceFeet(double poundforcefeet) + { + double value = (double) poundforcefeet; + return new Torque(value, TorqueUnit.PoundForceFoot); + } + /// + /// Get Torque from PoundForceInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromPoundForceInches(double poundforceinches) + { + double value = (double) poundforceinches; + return new Torque(value, TorqueUnit.PoundForceInch); + } + /// + /// Get Torque from TonneForceCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromTonneForceCentimeters(double tonneforcecentimeters) + { + double value = (double) tonneforcecentimeters; + return new Torque(value, TorqueUnit.TonneForceCentimeter); + } + /// + /// Get Torque from TonneForceMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromTonneForceMeters(double tonneforcemeters) + { + double value = (double) tonneforcemeters; + return new Torque(value, TorqueUnit.TonneForceMeter); + } + /// + /// Get Torque from TonneForceMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromTonneForceMillimeters(double tonneforcemillimeters) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Torque From(double value, TorqueUnit fromUnit) + { + return new Torque((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Torque Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Torque result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Torque result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TorqueUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TorqueUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..0d41dea4cf --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs @@ -0,0 +1,570 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 VitaminA : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VitaminAUnit? _unit; + + static VitaminA() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + /// + /// Creates the quantity with a value of 0 in the base unit InternationalUnit. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public VitaminA() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. + /// + public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; + + /// + /// 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 static QuantityType QuantityType => QuantityType.VitaminA; + + /// + /// All units of measurement for the VitaminA quantity. + /// + public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. + /// + public static VitaminA Zero => new VitaminA(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 VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VitaminA.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VitaminA.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get VitaminA in InternationalUnits. + /// + public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VitaminAUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get VitaminA from InternationalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VitaminA FromInternationalUnits(double internationalunits) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static VitaminA From(double value, VitaminAUnit fromUnit) + { + return new VitaminA((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 VitaminA Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out VitaminA result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 VitaminA result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VitaminAUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 VitaminAUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..4696c60bdd --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs @@ -0,0 +1,1284 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 Volume : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeUnit? _unit; + + static Volume() + { + BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit CubicMeter. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public Volume() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Volume, which is CubicMeter. All conversions go via this value. + /// + public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Volume; + + /// + /// All units of measurement for the Volume quantity. + /// + public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. + /// + public static Volume Zero => new Volume(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 VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Volume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Volume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Kiloliters. + /// + public double Kiloliters => As(VolumeUnit.Kiloliter); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Volume from AuTablespoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromAuTablespoons(double autablespoons) + { + double value = (double) autablespoons; + return new Volume(value, VolumeUnit.AuTablespoon); + } + /// + /// Get Volume from Centiliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCentiliters(double centiliters) + { + double value = (double) centiliters; + return new Volume(value, VolumeUnit.Centiliter); + } + /// + /// Get Volume from CubicCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicCentimeters(double cubiccentimeters) + { + double value = (double) cubiccentimeters; + return new Volume(value, VolumeUnit.CubicCentimeter); + } + /// + /// Get Volume from CubicDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicDecimeters(double cubicdecimeters) + { + double value = (double) cubicdecimeters; + return new Volume(value, VolumeUnit.CubicDecimeter); + } + /// + /// Get Volume from CubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicFeet(double cubicfeet) + { + double value = (double) cubicfeet; + return new Volume(value, VolumeUnit.CubicFoot); + } + /// + /// Get Volume from CubicInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicInches(double cubicinches) + { + double value = (double) cubicinches; + return new Volume(value, VolumeUnit.CubicInch); + } + /// + /// Get Volume from CubicKilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicKilometers(double cubickilometers) + { + double value = (double) cubickilometers; + return new Volume(value, VolumeUnit.CubicKilometer); + } + /// + /// Get Volume from CubicMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMeters(double cubicmeters) + { + double value = (double) cubicmeters; + return new Volume(value, VolumeUnit.CubicMeter); + } + /// + /// Get Volume from CubicMicrometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMicrometers(double cubicmicrometers) + { + double value = (double) cubicmicrometers; + return new Volume(value, VolumeUnit.CubicMicrometer); + } + /// + /// Get Volume from CubicMiles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMiles(double cubicmiles) + { + double value = (double) cubicmiles; + return new Volume(value, VolumeUnit.CubicMile); + } + /// + /// Get Volume from CubicMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMillimeters(double cubicmillimeters) + { + double value = (double) cubicmillimeters; + return new Volume(value, VolumeUnit.CubicMillimeter); + } + /// + /// Get Volume from CubicYards. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicYards(double cubicyards) + { + double value = (double) cubicyards; + return new Volume(value, VolumeUnit.CubicYard); + } + /// + /// Get Volume from Deciliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromDeciliters(double deciliters) + { + double value = (double) deciliters; + return new Volume(value, VolumeUnit.Deciliter); + } + /// + /// Get Volume from HectocubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromHectocubicFeet(double hectocubicfeet) + { + double value = (double) hectocubicfeet; + return new Volume(value, VolumeUnit.HectocubicFoot); + } + /// + /// Get Volume from HectocubicMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromHectocubicMeters(double hectocubicmeters) + { + double value = (double) hectocubicmeters; + return new Volume(value, VolumeUnit.HectocubicMeter); + } + /// + /// Get Volume from Hectoliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromHectoliters(double hectoliters) + { + double value = (double) hectoliters; + return new Volume(value, VolumeUnit.Hectoliter); + } + /// + /// Get Volume from ImperialBeerBarrels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromImperialBeerBarrels(double imperialbeerbarrels) + { + double value = (double) imperialbeerbarrels; + return new Volume(value, VolumeUnit.ImperialBeerBarrel); + } + /// + /// Get Volume from ImperialGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromImperialGallons(double imperialgallons) + { + double value = (double) imperialgallons; + return new Volume(value, VolumeUnit.ImperialGallon); + } + /// + /// Get Volume from ImperialOunces. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromImperialOunces(double imperialounces) + { + double value = (double) imperialounces; + return new Volume(value, VolumeUnit.ImperialOunce); + } + /// + /// Get Volume from KilocubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKilocubicFeet(double kilocubicfeet) + { + double value = (double) kilocubicfeet; + return new Volume(value, VolumeUnit.KilocubicFoot); + } + /// + /// Get Volume from KilocubicMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKilocubicMeters(double kilocubicmeters) + { + double value = (double) kilocubicmeters; + return new Volume(value, VolumeUnit.KilocubicMeter); + } + /// + /// Get Volume from KiloimperialGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKiloimperialGallons(double kiloimperialgallons) + { + double value = (double) kiloimperialgallons; + return new Volume(value, VolumeUnit.KiloimperialGallon); + } + /// + /// Get Volume from Kiloliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKiloliters(double kiloliters) + { + double value = (double) kiloliters; + return new Volume(value, VolumeUnit.Kiloliter); + } + /// + /// Get Volume from KilousGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKilousGallons(double kilousgallons) + { + double value = (double) kilousgallons; + return new Volume(value, VolumeUnit.KilousGallon); + } + /// + /// Get Volume from Liters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromLiters(double liters) + { + double value = (double) liters; + return new Volume(value, VolumeUnit.Liter); + } + /// + /// Get Volume from MegacubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMegacubicFeet(double megacubicfeet) + { + double value = (double) megacubicfeet; + return new Volume(value, VolumeUnit.MegacubicFoot); + } + /// + /// Get Volume from MegaimperialGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMegaimperialGallons(double megaimperialgallons) + { + double value = (double) megaimperialgallons; + return new Volume(value, VolumeUnit.MegaimperialGallon); + } + /// + /// Get Volume from MegausGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMegausGallons(double megausgallons) + { + double value = (double) megausgallons; + return new Volume(value, VolumeUnit.MegausGallon); + } + /// + /// Get Volume from MetricCups. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMetricCups(double metriccups) + { + double value = (double) metriccups; + return new Volume(value, VolumeUnit.MetricCup); + } + /// + /// Get Volume from MetricTeaspoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMetricTeaspoons(double metricteaspoons) + { + double value = (double) metricteaspoons; + return new Volume(value, VolumeUnit.MetricTeaspoon); + } + /// + /// Get Volume from Microliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMicroliters(double microliters) + { + double value = (double) microliters; + return new Volume(value, VolumeUnit.Microliter); + } + /// + /// Get Volume from Milliliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMilliliters(double milliliters) + { + double value = (double) milliliters; + return new Volume(value, VolumeUnit.Milliliter); + } + /// + /// Get Volume from OilBarrels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromOilBarrels(double oilbarrels) + { + double value = (double) oilbarrels; + return new Volume(value, VolumeUnit.OilBarrel); + } + /// + /// Get Volume from UkTablespoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUkTablespoons(double uktablespoons) + { + double value = (double) uktablespoons; + return new Volume(value, VolumeUnit.UkTablespoon); + } + /// + /// Get Volume from UsBeerBarrels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsBeerBarrels(double usbeerbarrels) + { + double value = (double) usbeerbarrels; + return new Volume(value, VolumeUnit.UsBeerBarrel); + } + /// + /// Get Volume from UsCustomaryCups. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsCustomaryCups(double uscustomarycups) + { + double value = (double) uscustomarycups; + return new Volume(value, VolumeUnit.UsCustomaryCup); + } + /// + /// Get Volume from UsGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsGallons(double usgallons) + { + double value = (double) usgallons; + return new Volume(value, VolumeUnit.UsGallon); + } + /// + /// Get Volume from UsLegalCups. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsLegalCups(double uslegalcups) + { + double value = (double) uslegalcups; + return new Volume(value, VolumeUnit.UsLegalCup); + } + /// + /// Get Volume from UsOunces. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsOunces(double usounces) + { + double value = (double) usounces; + return new Volume(value, VolumeUnit.UsOunce); + } + /// + /// Get Volume from UsPints. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsPints(double uspints) + { + double value = (double) uspints; + return new Volume(value, VolumeUnit.UsPint); + } + /// + /// Get Volume from UsQuarts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsQuarts(double usquarts) + { + double value = (double) usquarts; + return new Volume(value, VolumeUnit.UsQuart); + } + /// + /// Get Volume from UsTablespoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsTablespoons(double ustablespoons) + { + double value = (double) ustablespoons; + return new Volume(value, VolumeUnit.UsTablespoon); + } + /// + /// Get Volume from UsTeaspoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsTeaspoons(double usteaspoons) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Volume From(double value, VolumeUnit fromUnit) + { + return new Volume((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Volume Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Volume result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Volume result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 VolumeUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.Kiloliter: return (_value/1e3) * 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.Kiloliter: return (baseUnitValue*1e3) / 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } + } +} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs new file mode 100644 index 0000000000..4b90abd00c --- /dev/null +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs @@ -0,0 +1,995 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + // 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 VolumeFlow : IQuantity + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeFlowUnit? _unit; + + static VolumeFlow() + { + BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); + } + /// + /// Creates the quantity with a value of 0 in the base unit CubicMeterPerSecond. + /// + /// + /// Windows Runtime Component requires a default constructor. + /// + public VolumeFlow() + { + _value = 0; + _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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. + /// + public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.VolumeFlow; + + /// + /// All units of measurement for the VolumeFlow quantity. + /// + public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. + /// + public static VolumeFlow Zero => new VolumeFlow(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 VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VolumeFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeFlowUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get VolumeFlow from CentilitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCentilitersPerMinute(double centilitersperminute) + { + double value = (double) centilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); + } + /// + /// Get VolumeFlow from CubicDecimetersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) + { + double value = (double) cubicdecimetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); + } + /// + /// Get VolumeFlow from CubicFeetPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicFeetPerHour(double cubicfeetperhour) + { + double value = (double) cubicfeetperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); + } + /// + /// Get VolumeFlow from CubicFeetPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicFeetPerMinute(double cubicfeetperminute) + { + double value = (double) cubicfeetperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); + } + /// + /// Get VolumeFlow from CubicFeetPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicFeetPerSecond(double cubicfeetpersecond) + { + double value = (double) cubicfeetpersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); + } + /// + /// Get VolumeFlow from CubicMetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicMetersPerHour(double cubicmetersperhour) + { + double value = (double) cubicmetersperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); + } + /// + /// Get VolumeFlow from CubicMetersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicMetersPerMinute(double cubicmetersperminute) + { + double value = (double) cubicmetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); + } + /// + /// Get VolumeFlow from CubicMetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicMetersPerSecond(double cubicmeterspersecond) + { + double value = (double) cubicmeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); + } + /// + /// Get VolumeFlow from CubicYardsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicYardsPerHour(double cubicyardsperhour) + { + double value = (double) cubicyardsperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); + } + /// + /// Get VolumeFlow from CubicYardsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicYardsPerMinute(double cubicyardsperminute) + { + double value = (double) cubicyardsperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); + } + /// + /// Get VolumeFlow from CubicYardsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicYardsPerSecond(double cubicyardspersecond) + { + double value = (double) cubicyardspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); + } + /// + /// Get VolumeFlow from DecilitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromDecilitersPerMinute(double decilitersperminute) + { + double value = (double) decilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); + } + /// + /// Get VolumeFlow from KilolitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromKilolitersPerMinute(double kilolitersperminute) + { + double value = (double) kilolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); + } + /// + /// Get VolumeFlow from LitersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromLitersPerHour(double litersperhour) + { + double value = (double) litersperhour; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); + } + /// + /// Get VolumeFlow from LitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromLitersPerMinute(double litersperminute) + { + double value = (double) litersperminute; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); + } + /// + /// Get VolumeFlow from LitersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromLitersPerSecond(double literspersecond) + { + double value = (double) literspersecond; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); + } + /// + /// Get VolumeFlow from MicrolitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromMicrolitersPerMinute(double microlitersperminute) + { + double value = (double) microlitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); + } + /// + /// Get VolumeFlow from MillilitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromMillilitersPerMinute(double millilitersperminute) + { + double value = (double) millilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); + } + /// + /// Get VolumeFlow from MillionUsGallonsPerDay. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) + { + double value = (double) millionusgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); + } + /// + /// Get VolumeFlow from NanolitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromNanolitersPerMinute(double nanolitersperminute) + { + double value = (double) nanolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); + } + /// + /// Get VolumeFlow from OilBarrelsPerDay. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromOilBarrelsPerDay(double oilbarrelsperday) + { + double value = (double) oilbarrelsperday; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); + } + /// + /// Get VolumeFlow from OilBarrelsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromOilBarrelsPerHour(double oilbarrelsperhour) + { + double value = (double) oilbarrelsperhour; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); + } + /// + /// Get VolumeFlow from OilBarrelsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromOilBarrelsPerMinute(double oilbarrelsperminute) + { + double value = (double) oilbarrelsperminute; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromUsGallonsPerHour(double usgallonsperhour) + { + double value = (double) usgallonsperhour; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); + } + /// + /// Get VolumeFlow from UsGallonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromUsGallonsPerMinute(double usgallonsperminute) + { + double value = (double) usgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromUsGallonsPerSecond(double usgallonspersecond) + { + 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. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) + { + return new VolumeFlow((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 VolumeFlow Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out VolumeFlow result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 VolumeFlow result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VolumeFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 VolumeFlowUnit unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #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 + internal 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) + { + var provider = cultureName; + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) + { + var provider = cultureName; + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + { + var provider = GetFormatProviderFromCultureName(cultureName); + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #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 42dc4f39c1..e254fd55f5 100644 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj +++ b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj @@ -20,7 +20,13 @@ ..\Artifacts\UnitsNet.WindowsRuntimeComponent CS1701;CS1702;CS1705;CS0618;CS0809;CS1591 7.3 + + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + AnyCPU true @@ -210,6 +216,7 @@ 11.1.0 + 4.5.0 diff --git a/UnitsNet/GeneratedCode/Quantities/.gitignore b/UnitsNet/GeneratedCode/Quantities/.gitignore deleted file mode 100644 index 0360dd5ae9..0000000000 --- a/UnitsNet/GeneratedCode/Quantities/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.g.cs -!Information.NetFramework.g.cs -!Length.NetFramework.g.cs -!Level.NetFramework.g.cs diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs new file mode 100644 index 0000000000..571ee22b18 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs @@ -0,0 +1,792 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Acceleration : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AccelerationUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. + /// + public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Acceleration; + + /// + /// All units of measurement for the Acceleration quantity. + /// + public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. + /// + public static Acceleration Zero => new Acceleration(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 AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Acceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Acceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AccelerationUnit 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(AccelerationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Acceleration from CentimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centimeterspersecondsquared) + { + double value = (double) centimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); + } + /// + /// Get Acceleration from DecimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimeterspersecondsquared) + { + double value = (double) decimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); + } + /// + /// Get Acceleration from FeetPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) + { + double value = (double) feetpersecondsquared; + return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); + } + /// + /// Get Acceleration from InchesPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) + { + double value = (double) inchespersecondsquared; + return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); + } + /// + /// Get Acceleration from KilometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilometerspersecondsquared) + { + double value = (double) kilometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); + } + /// + /// Get Acceleration from KnotsPerHour. + /// + /// If value is NaN or Infinity. + public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) + { + double value = (double) knotsperhour; + return new Acceleration(value, AccelerationUnit.KnotPerHour); + } + /// + /// Get Acceleration from KnotsPerMinute. + /// + /// If value is NaN or Infinity. + public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) + { + double value = (double) knotsperminute; + return new Acceleration(value, AccelerationUnit.KnotPerMinute); + } + /// + /// Get Acceleration from KnotsPerSecond. + /// + /// If value is NaN or Infinity. + public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) + { + double value = (double) knotspersecond; + return new Acceleration(value, AccelerationUnit.KnotPerSecond); + } + /// + /// Get Acceleration from MetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersecondsquared) + { + double value = (double) meterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); + } + /// + /// Get Acceleration from MicrometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromMicrometersPerSecondSquared(QuantityValue micrometerspersecondsquared) + { + double value = (double) micrometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); + } + /// + /// Get Acceleration from MillimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millimeterspersecondsquared) + { + double value = (double) millimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); + } + /// + /// Get Acceleration from NanometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanometerspersecondsquared) + { + double value = (double) nanometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); + } + /// + /// Get Acceleration from StandardGravity. + /// + /// If value is NaN or Infinity. + public static Acceleration FromStandardGravity(QuantityValue standardgravity) + { + 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. + public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) + { + return new Acceleration((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Acceleration Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Acceleration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Acceleration result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AccelerationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Acceleration operator -(Acceleration right) + { + return new Acceleration(-right.Value, right.Unit); + } + + public static Acceleration operator +(Acceleration left, Acceleration right) + { + return new Acceleration(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Acceleration operator -(Acceleration left, Acceleration right) + { + return new Acceleration(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Acceleration operator *(double left, Acceleration right) + { + return new Acceleration(left * right.Value, right.Unit); + } + + public static Acceleration operator *(Acceleration left, double right) + { + return new Acceleration(left.Value * right, left.Unit); + } + + public static Acceleration operator /(Acceleration left, double right) + { + return new Acceleration(left.Value / right, left.Unit); + } + + public static double operator /(Acceleration left, Acceleration right) + { + return left.MetersPerSecondSquared / right.MetersPerSecondSquared; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Acceleration left, Acceleration right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Acceleration left, Acceleration right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Acceleration left, Acceleration right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Acceleration left, Acceleration 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs new file mode 100644 index 0000000000..c73bbd675f --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs @@ -0,0 +1,808 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct AmountOfSubstance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AmountOfSubstanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. + /// + public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AmountOfSubstance; + + /// + /// All units of measurement for the AmountOfSubstance quantity. + /// + public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Mole. + /// + public static AmountOfSubstance Zero => new AmountOfSubstance(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 AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmountOfSubstance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AmountOfSubstanceUnit 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(AmountOfSubstanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AmountOfSubstance from Centimoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) + { + double value = (double) centimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); + } + /// + /// Get AmountOfSubstance from CentipoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) + { + double value = (double) centipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); + } + /// + /// Get AmountOfSubstance from Decimoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) + { + double value = (double) decimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); + } + /// + /// Get AmountOfSubstance from DecipoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) + { + double value = (double) decipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); + } + /// + /// Get AmountOfSubstance from Kilomoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) + { + double value = (double) kilomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); + } + /// + /// Get AmountOfSubstance from KilopoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) + { + double value = (double) kilopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); + } + /// + /// Get AmountOfSubstance from Micromoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) + { + double value = (double) micromoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); + } + /// + /// Get AmountOfSubstance from MicropoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) + { + double value = (double) micropoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); + } + /// + /// Get AmountOfSubstance from Millimoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) + { + double value = (double) millimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); + } + /// + /// Get AmountOfSubstance from MillipoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) + { + double value = (double) millipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); + } + /// + /// Get AmountOfSubstance from Moles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMoles(QuantityValue moles) + { + double value = (double) moles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); + } + /// + /// Get AmountOfSubstance from Nanomoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) + { + double value = (double) nanomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); + } + /// + /// Get AmountOfSubstance from NanopoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) + { + double value = (double) nanopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); + } + /// + /// Get AmountOfSubstance from PoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) + { + 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. + public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) + { + return new AmountOfSubstance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AmountOfSubstance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AmountOfSubstance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AmountOfSubstanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static AmountOfSubstance operator -(AmountOfSubstance right) + { + return new AmountOfSubstance(-right.Value, right.Unit); + } + + public static AmountOfSubstance operator +(AmountOfSubstance left, AmountOfSubstance right) + { + return new AmountOfSubstance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static AmountOfSubstance operator -(AmountOfSubstance left, AmountOfSubstance right) + { + return new AmountOfSubstance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static AmountOfSubstance operator *(double left, AmountOfSubstance right) + { + return new AmountOfSubstance(left * right.Value, right.Unit); + } + + public static AmountOfSubstance operator *(AmountOfSubstance left, double right) + { + return new AmountOfSubstance(left.Value * right, left.Unit); + } + + public static AmountOfSubstance operator /(AmountOfSubstance left, double right) + { + return new AmountOfSubstance(left.Value / right, left.Unit); + } + + public static double operator /(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Moles / right.Moles; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(AmountOfSubstance left, AmountOfSubstance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs new file mode 100644 index 0000000000..0996a6c36c --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs @@ -0,0 +1,656 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. + /// + public partial struct AmplitudeRatio : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AmplitudeRatioUnit? _unit; + + static AmplitudeRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. + /// + public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AmplitudeRatio; + + /// + /// All units of measurement for the AmplitudeRatio quantity. + /// + public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. + /// + public static AmplitudeRatio Zero => new AmplitudeRatio(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 AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmplitudeRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AmplitudeRatioUnit 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(AmplitudeRatioUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AmplitudeRatio from DecibelMicrovolts. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) + { + double value = (double) decibelmicrovolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); + } + /// + /// Get AmplitudeRatio from DecibelMillivolts. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) + { + double value = (double) decibelmillivolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); + } + /// + /// Get AmplitudeRatio from DecibelsUnloaded. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) + { + double value = (double) decibelsunloaded; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); + } + /// + /// Get AmplitudeRatio from DecibelVolts. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) + { + 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. + public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) + { + return new AmplitudeRatio((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AmplitudeRatio Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AmplitudeRatio result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AmplitudeRatioUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AmplitudeRatioUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Logarithmic Arithmetic Operators + + public static AmplitudeRatio operator -(AmplitudeRatio right) + { + return new AmplitudeRatio(-right.Value, right.Unit); + } + + public static AmplitudeRatio operator +(AmplitudeRatio left, AmplitudeRatio right) + { + // Logarithmic addition + // Formula: 20*log10(10^(x/20) + 10^(y/20)) + return new AmplitudeRatio(20*Math.Log10(Math.Pow(10, left.Value/20) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/20)), left.Unit); + } + + public static AmplitudeRatio operator -(AmplitudeRatio left, AmplitudeRatio right) + { + // Logarithmic subtraction + // Formula: 20*log10(10^(x/20) - 10^(y/20)) + return new AmplitudeRatio(20*Math.Log10(Math.Pow(10, left.Value/20) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/20)), left.Unit); + } + + public static AmplitudeRatio operator *(double left, AmplitudeRatio right) + { + // Logarithmic multiplication = addition + return new AmplitudeRatio(left + right.Value, right.Unit); + } + + public static AmplitudeRatio operator *(AmplitudeRatio left, double right) + { + // Logarithmic multiplication = addition + return new AmplitudeRatio(left.Value + (double)right, left.Unit); + } + + public static AmplitudeRatio operator /(AmplitudeRatio left, double right) + { + // Logarithmic division = subtraction + return new AmplitudeRatio(left.Value - (double)right, left.Unit); + } + + public static double operator /(AmplitudeRatio left, AmplitudeRatio right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(AmplitudeRatio left, AmplitudeRatio 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs new file mode 100644 index 0000000000..5c05c6b4b2 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs @@ -0,0 +1,808 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Angle : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AngleUnit? _unit; + + static Angle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Angle, which is Degree. All conversions go via this value. + /// + public static AngleUnit BaseUnit => AngleUnit.Degree; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Angle; + + /// + /// All units of measurement for the Angle quantity. + /// + public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Degree. + /// + public static Angle Zero => new Angle(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 AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Angle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Angle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AngleUnit 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(AngleUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Angle from Arcminutes. + /// + /// If value is NaN or Infinity. + public static Angle FromArcminutes(QuantityValue arcminutes) + { + double value = (double) arcminutes; + return new Angle(value, AngleUnit.Arcminute); + } + /// + /// Get Angle from Arcseconds. + /// + /// If value is NaN or Infinity. + public static Angle FromArcseconds(QuantityValue arcseconds) + { + double value = (double) arcseconds; + return new Angle(value, AngleUnit.Arcsecond); + } + /// + /// Get Angle from Centiradians. + /// + /// If value is NaN or Infinity. + public static Angle FromCentiradians(QuantityValue centiradians) + { + double value = (double) centiradians; + return new Angle(value, AngleUnit.Centiradian); + } + /// + /// Get Angle from Deciradians. + /// + /// If value is NaN or Infinity. + public static Angle FromDeciradians(QuantityValue deciradians) + { + double value = (double) deciradians; + return new Angle(value, AngleUnit.Deciradian); + } + /// + /// Get Angle from Degrees. + /// + /// If value is NaN or Infinity. + public static Angle FromDegrees(QuantityValue degrees) + { + double value = (double) degrees; + return new Angle(value, AngleUnit.Degree); + } + /// + /// Get Angle from Gradians. + /// + /// If value is NaN or Infinity. + public static Angle FromGradians(QuantityValue gradians) + { + double value = (double) gradians; + return new Angle(value, AngleUnit.Gradian); + } + /// + /// Get Angle from Microdegrees. + /// + /// If value is NaN or Infinity. + public static Angle FromMicrodegrees(QuantityValue microdegrees) + { + double value = (double) microdegrees; + return new Angle(value, AngleUnit.Microdegree); + } + /// + /// Get Angle from Microradians. + /// + /// If value is NaN or Infinity. + public static Angle FromMicroradians(QuantityValue microradians) + { + double value = (double) microradians; + return new Angle(value, AngleUnit.Microradian); + } + /// + /// Get Angle from Millidegrees. + /// + /// If value is NaN or Infinity. + public static Angle FromMillidegrees(QuantityValue millidegrees) + { + double value = (double) millidegrees; + return new Angle(value, AngleUnit.Millidegree); + } + /// + /// Get Angle from Milliradians. + /// + /// If value is NaN or Infinity. + public static Angle FromMilliradians(QuantityValue milliradians) + { + double value = (double) milliradians; + return new Angle(value, AngleUnit.Milliradian); + } + /// + /// Get Angle from Nanodegrees. + /// + /// If value is NaN or Infinity. + public static Angle FromNanodegrees(QuantityValue nanodegrees) + { + double value = (double) nanodegrees; + return new Angle(value, AngleUnit.Nanodegree); + } + /// + /// Get Angle from Nanoradians. + /// + /// If value is NaN or Infinity. + public static Angle FromNanoradians(QuantityValue nanoradians) + { + double value = (double) nanoradians; + return new Angle(value, AngleUnit.Nanoradian); + } + /// + /// Get Angle from Radians. + /// + /// If value is NaN or Infinity. + public static Angle FromRadians(QuantityValue radians) + { + double value = (double) radians; + return new Angle(value, AngleUnit.Radian); + } + /// + /// Get Angle from Revolutions. + /// + /// If value is NaN or Infinity. + public static Angle FromRevolutions(QuantityValue revolutions) + { + 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. + public static Angle From(QuantityValue value, AngleUnit fromUnit) + { + return new Angle((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Angle Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Angle result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Angle result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AngleUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AngleUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Angle operator -(Angle right) + { + return new Angle(-right.Value, right.Unit); + } + + public static Angle operator +(Angle left, Angle right) + { + return new Angle(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Angle operator -(Angle left, Angle right) + { + return new Angle(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Angle operator *(double left, Angle right) + { + return new Angle(left * right.Value, right.Unit); + } + + public static Angle operator *(Angle left, double right) + { + return new Angle(left.Value * right, left.Unit); + } + + public static Angle operator /(Angle left, double right) + { + return new Angle(left.Value / right, left.Unit); + } + + public static double operator /(Angle left, Angle right) + { + return left.Degrees / right.Degrees; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Angle left, Angle right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Angle left, Angle right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Angle left, Angle right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Angle left, Angle 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs new file mode 100644 index 0000000000..472ad59e8f --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ApparentEnergy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentEnergyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. + /// + public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ApparentEnergy; + + /// + /// All units of measurement for the ApparentEnergy quantity. + /// + public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. + /// + public static ApparentEnergy Zero => new ApparentEnergy(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 ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ApparentEnergyUnit 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(ApparentEnergyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ApparentEnergy from KilovoltampereHours. + /// + /// If value is NaN or Infinity. + public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) + { + double value = (double) kilovoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); + } + /// + /// Get ApparentEnergy from MegavoltampereHours. + /// + /// If value is NaN or Infinity. + public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) + { + double value = (double) megavoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); + } + /// + /// Get ApparentEnergy from VoltampereHours. + /// + /// If value is NaN or Infinity. + public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) + { + 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. + public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) + { + return new ApparentEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ApparentEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ApparentEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ApparentEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ApparentEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ApparentEnergy operator -(ApparentEnergy right) + { + return new ApparentEnergy(-right.Value, right.Unit); + } + + public static ApparentEnergy operator +(ApparentEnergy left, ApparentEnergy right) + { + return new ApparentEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ApparentEnergy operator -(ApparentEnergy left, ApparentEnergy right) + { + return new ApparentEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ApparentEnergy operator *(double left, ApparentEnergy right) + { + return new ApparentEnergy(left * right.Value, right.Unit); + } + + public static ApparentEnergy operator *(ApparentEnergy left, double right) + { + return new ApparentEnergy(left.Value * right, left.Unit); + } + + public static ApparentEnergy operator /(ApparentEnergy left, double right) + { + return new ApparentEnergy(left.Value / right, left.Unit); + } + + public static double operator /(ApparentEnergy left, ApparentEnergy right) + { + return left.VoltampereHours / right.VoltampereHours; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ApparentEnergy left, ApparentEnergy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ApparentEnergy left, ApparentEnergy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ApparentEnergy left, ApparentEnergy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ApparentEnergy left, ApparentEnergy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs new file mode 100644 index 0000000000..97b13fdfb4 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs @@ -0,0 +1,648 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ApparentPower : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentPowerUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. + /// + public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ApparentPower; + + /// + /// All units of measurement for the ApparentPower quantity. + /// + public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. + /// + public static ApparentPower Zero => new ApparentPower(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 ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentPower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentPower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ApparentPowerUnit 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(ApparentPowerUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ApparentPower from Gigavoltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) + { + double value = (double) gigavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); + } + /// + /// Get ApparentPower from Kilovoltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) + { + double value = (double) kilovoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); + } + /// + /// Get ApparentPower from Megavoltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) + { + double value = (double) megavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); + } + /// + /// Get ApparentPower from Voltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromVoltamperes(QuantityValue voltamperes) + { + 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. + public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) + { + return new ApparentPower((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ApparentPower Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ApparentPower result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ApparentPower result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ApparentPowerUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ApparentPowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ApparentPowerUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ApparentPower operator -(ApparentPower right) + { + return new ApparentPower(-right.Value, right.Unit); + } + + public static ApparentPower operator +(ApparentPower left, ApparentPower right) + { + return new ApparentPower(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ApparentPower operator -(ApparentPower left, ApparentPower right) + { + return new ApparentPower(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ApparentPower operator *(double left, ApparentPower right) + { + return new ApparentPower(left * right.Value, right.Unit); + } + + public static ApparentPower operator *(ApparentPower left, double right) + { + return new ApparentPower(left.Value * right, left.Unit); + } + + public static ApparentPower operator /(ApparentPower left, double right) + { + return new ApparentPower(left.Value / right, left.Unit); + } + + public static double operator /(ApparentPower left, ApparentPower right) + { + return left.Voltamperes / right.Voltamperes; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ApparentPower left, ApparentPower right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ApparentPower left, ApparentPower right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ApparentPower left, ApparentPower right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ApparentPower left, ApparentPower 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs new file mode 100644 index 0000000000..328946fdad --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs @@ -0,0 +1,792 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct Area : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Area, which is SquareMeter. All conversions go via this value. + /// + public static AreaUnit BaseUnit => AreaUnit.SquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Area; + + /// + /// All units of measurement for the Area quantity. + /// + public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. + /// + public static Area Zero => new Area(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 AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Area.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Area.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaUnit 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(AreaUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Area from Acres. + /// + /// If value is NaN or Infinity. + public static Area FromAcres(QuantityValue acres) + { + double value = (double) acres; + return new Area(value, AreaUnit.Acre); + } + /// + /// Get Area from Hectares. + /// + /// If value is NaN or Infinity. + public static Area FromHectares(QuantityValue hectares) + { + double value = (double) hectares; + return new Area(value, AreaUnit.Hectare); + } + /// + /// Get Area from SquareCentimeters. + /// + /// If value is NaN or Infinity. + public static Area FromSquareCentimeters(QuantityValue squarecentimeters) + { + double value = (double) squarecentimeters; + return new Area(value, AreaUnit.SquareCentimeter); + } + /// + /// Get Area from SquareDecimeters. + /// + /// If value is NaN or Infinity. + public static Area FromSquareDecimeters(QuantityValue squaredecimeters) + { + double value = (double) squaredecimeters; + return new Area(value, AreaUnit.SquareDecimeter); + } + /// + /// Get Area from SquareFeet. + /// + /// If value is NaN or Infinity. + public static Area FromSquareFeet(QuantityValue squarefeet) + { + double value = (double) squarefeet; + return new Area(value, AreaUnit.SquareFoot); + } + /// + /// Get Area from SquareInches. + /// + /// If value is NaN or Infinity. + public static Area FromSquareInches(QuantityValue squareinches) + { + double value = (double) squareinches; + return new Area(value, AreaUnit.SquareInch); + } + /// + /// Get Area from SquareKilometers. + /// + /// If value is NaN or Infinity. + public static Area FromSquareKilometers(QuantityValue squarekilometers) + { + double value = (double) squarekilometers; + return new Area(value, AreaUnit.SquareKilometer); + } + /// + /// Get Area from SquareMeters. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMeters(QuantityValue squaremeters) + { + double value = (double) squaremeters; + return new Area(value, AreaUnit.SquareMeter); + } + /// + /// Get Area from SquareMicrometers. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMicrometers(QuantityValue squaremicrometers) + { + double value = (double) squaremicrometers; + return new Area(value, AreaUnit.SquareMicrometer); + } + /// + /// Get Area from SquareMiles. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMiles(QuantityValue squaremiles) + { + double value = (double) squaremiles; + return new Area(value, AreaUnit.SquareMile); + } + /// + /// Get Area from SquareMillimeters. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMillimeters(QuantityValue squaremillimeters) + { + double value = (double) squaremillimeters; + return new Area(value, AreaUnit.SquareMillimeter); + } + /// + /// Get Area from SquareYards. + /// + /// If value is NaN or Infinity. + public static Area FromSquareYards(QuantityValue squareyards) + { + double value = (double) squareyards; + return new Area(value, AreaUnit.SquareYard); + } + /// + /// Get Area from UsSurveySquareFeet. + /// + /// If value is NaN or Infinity. + public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) + { + 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. + public static Area From(QuantityValue value, AreaUnit fromUnit) + { + return new Area((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Area Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Area result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Area result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AreaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AreaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Area operator -(Area right) + { + return new Area(-right.Value, right.Unit); + } + + public static Area operator +(Area left, Area right) + { + return new Area(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Area operator -(Area left, Area right) + { + return new Area(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Area operator *(double left, Area right) + { + return new Area(left * right.Value, right.Unit); + } + + public static Area operator *(Area left, double right) + { + return new Area(left.Value * right, left.Unit); + } + + public static Area operator /(Area left, double right) + { + return new Area(left.Value / right, left.Unit); + } + + public static double operator /(Area left, Area right) + { + return left.SquareMeters / right.SquareMeters; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Area left, Area right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Area left, Area right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Area left, Area right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Area left, Area 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs new file mode 100644 index 0000000000..c288aa6440 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs @@ -0,0 +1,600 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The area density of a two-dimensional object is calculated as the mass per unit area. + /// + public partial struct AreaDensity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaDensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. + /// + public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AreaDensity; + + /// + /// All units of measurement for the AreaDensity quantity. + /// + public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. + /// + public static AreaDensity Zero => new AreaDensity(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 AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AreaDensity in KilogramsPerSquareMeter. + /// + public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaDensityUnit 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(AreaDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AreaDensity from KilogramsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) + { + 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. + public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) + { + return new AreaDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AreaDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AreaDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AreaDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AreaDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AreaDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static AreaDensity operator -(AreaDensity right) + { + return new AreaDensity(-right.Value, right.Unit); + } + + public static AreaDensity operator +(AreaDensity left, AreaDensity right) + { + return new AreaDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static AreaDensity operator -(AreaDensity left, AreaDensity right) + { + return new AreaDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static AreaDensity operator *(double left, AreaDensity right) + { + return new AreaDensity(left * right.Value, right.Unit); + } + + public static AreaDensity operator *(AreaDensity left, double right) + { + return new AreaDensity(left.Value * right, left.Unit); + } + + public static AreaDensity operator /(AreaDensity left, double right) + { + return new AreaDensity(left.Value / right, left.Unit); + } + + public static double operator /(AreaDensity left, AreaDensity right) + { + return left.KilogramsPerSquareMeter / right.KilogramsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(AreaDensity left, AreaDensity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(AreaDensity left, AreaDensity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(AreaDensity left, AreaDensity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(AreaDensity left, AreaDensity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs new file mode 100644 index 0000000000..83b7e00bb2 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs @@ -0,0 +1,680 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// A geometric property of an area that reflects how its points are distributed with regard to an axis. + /// + public partial struct AreaMomentOfInertia : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaMomentOfInertiaUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. + /// + public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; + + /// + /// 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 static QuantityType QuantityType => QuantityType.AreaMomentOfInertia; + + /// + /// All units of measurement for the AreaMomentOfInertia quantity. + /// + public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. + /// + public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(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 AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaMomentOfInertiaUnit 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(AreaMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AreaMomentOfInertia from CentimetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) + { + double value = (double) centimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from DecimetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) + { + double value = (double) decimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from FeetToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) + { + double value = (double) feettothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); + } + /// + /// Get AreaMomentOfInertia from InchesToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) + { + double value = (double) inchestothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) + { + double value = (double) meterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MillimetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) + { + 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. + public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) + { + return new AreaMomentOfInertia((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 AreaMomentOfInertia Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 AreaMomentOfInertia result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 AreaMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static AreaMomentOfInertia operator -(AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(-right.Value, right.Unit); + } + + public static AreaMomentOfInertia operator +(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static AreaMomentOfInertia operator -(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static AreaMomentOfInertia operator *(double left, AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(left * right.Value, right.Unit); + } + + public static AreaMomentOfInertia operator *(AreaMomentOfInertia left, double right) + { + return new AreaMomentOfInertia(left.Value * right, left.Unit); + } + + public static AreaMomentOfInertia operator /(AreaMomentOfInertia left, double right) + { + return new AreaMomentOfInertia(left.Value / right, left.Unit); + } + + public static double operator /(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.MetersToTheFourth / right.MetersToTheFourth; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(AreaMomentOfInertia left, AreaMomentOfInertia 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs new file mode 100644 index 0000000000..60d0bbce91 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs @@ -0,0 +1,1003 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Bit_rate + /// + public partial struct BitRate : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BitRateUnit? _unit; + + static BitRate() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. + /// + public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.BitRate; + + /// + /// All units of measurement for the BitRate quantity. + /// + public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. + /// + public static BitRate Zero => new BitRate(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 BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BitRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BitRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BitRateUnit 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(BitRateUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get BitRate from BitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) + { + decimal value = (decimal) bitspersecond; + return new BitRate(value, BitRateUnit.BitPerSecond); + } + /// + /// Get BitRate from BytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) + { + decimal value = (decimal) bytespersecond; + return new BitRate(value, BitRateUnit.BytePerSecond); + } + /// + /// Get BitRate from ExabitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) + { + decimal value = (decimal) exabitspersecond; + return new BitRate(value, BitRateUnit.ExabitPerSecond); + } + /// + /// Get BitRate from ExabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) + { + decimal value = (decimal) exabytespersecond; + return new BitRate(value, BitRateUnit.ExabytePerSecond); + } + /// + /// Get BitRate from ExbibitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) + { + decimal value = (decimal) exbibitspersecond; + return new BitRate(value, BitRateUnit.ExbibitPerSecond); + } + /// + /// Get BitRate from ExbibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) + { + decimal value = (decimal) exbibytespersecond; + return new BitRate(value, BitRateUnit.ExbibytePerSecond); + } + /// + /// Get BitRate from GibibitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) + { + decimal value = (decimal) gibibitspersecond; + return new BitRate(value, BitRateUnit.GibibitPerSecond); + } + /// + /// Get BitRate from GibibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) + { + decimal value = (decimal) gibibytespersecond; + return new BitRate(value, BitRateUnit.GibibytePerSecond); + } + /// + /// Get BitRate from GigabitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) + { + decimal value = (decimal) gigabitspersecond; + return new BitRate(value, BitRateUnit.GigabitPerSecond); + } + /// + /// Get BitRate from GigabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) + { + decimal value = (decimal) gigabytespersecond; + return new BitRate(value, BitRateUnit.GigabytePerSecond); + } + /// + /// Get BitRate from KibibitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) + { + decimal value = (decimal) kibibitspersecond; + return new BitRate(value, BitRateUnit.KibibitPerSecond); + } + /// + /// Get BitRate from KibibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) + { + decimal value = (decimal) kibibytespersecond; + return new BitRate(value, BitRateUnit.KibibytePerSecond); + } + /// + /// Get BitRate from KilobitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) + { + decimal value = (decimal) kilobitspersecond; + return new BitRate(value, BitRateUnit.KilobitPerSecond); + } + /// + /// Get BitRate from KilobytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) + { + decimal value = (decimal) kilobytespersecond; + return new BitRate(value, BitRateUnit.KilobytePerSecond); + } + /// + /// Get BitRate from MebibitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) + { + decimal value = (decimal) mebibitspersecond; + return new BitRate(value, BitRateUnit.MebibitPerSecond); + } + /// + /// Get BitRate from MebibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) + { + decimal value = (decimal) mebibytespersecond; + return new BitRate(value, BitRateUnit.MebibytePerSecond); + } + /// + /// Get BitRate from MegabitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) + { + decimal value = (decimal) megabitspersecond; + return new BitRate(value, BitRateUnit.MegabitPerSecond); + } + /// + /// Get BitRate from MegabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) + { + decimal value = (decimal) megabytespersecond; + return new BitRate(value, BitRateUnit.MegabytePerSecond); + } + /// + /// Get BitRate from PebibitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) + { + decimal value = (decimal) pebibitspersecond; + return new BitRate(value, BitRateUnit.PebibitPerSecond); + } + /// + /// Get BitRate from PebibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) + { + decimal value = (decimal) pebibytespersecond; + return new BitRate(value, BitRateUnit.PebibytePerSecond); + } + /// + /// Get BitRate from PetabitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) + { + decimal value = (decimal) petabitspersecond; + return new BitRate(value, BitRateUnit.PetabitPerSecond); + } + /// + /// Get BitRate from PetabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) + { + decimal value = (decimal) petabytespersecond; + return new BitRate(value, BitRateUnit.PetabytePerSecond); + } + /// + /// Get BitRate from TebibitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) + { + decimal value = (decimal) tebibitspersecond; + return new BitRate(value, BitRateUnit.TebibitPerSecond); + } + /// + /// Get BitRate from TebibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) + { + decimal value = (decimal) tebibytespersecond; + return new BitRate(value, BitRateUnit.TebibytePerSecond); + } + /// + /// Get BitRate from TerabitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) + { + decimal value = (decimal) terabitspersecond; + return new BitRate(value, BitRateUnit.TerabitPerSecond); + } + /// + /// Get BitRate from TerabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) + { + 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. + public static BitRate From(QuantityValue value, BitRateUnit fromUnit) + { + return new BitRate((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 BitRate Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 BitRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out BitRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 BitRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 BitRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out BitRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 BitRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static BitRate operator -(BitRate right) + { + return new BitRate(-right.Value, right.Unit); + } + + public static BitRate operator +(BitRate left, BitRate right) + { + return new BitRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static BitRate operator -(BitRate left, BitRate right) + { + return new BitRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static BitRate operator *(decimal left, BitRate right) + { + return new BitRate(left * right.Value, right.Unit); + } + + public static BitRate operator *(BitRate left, decimal right) + { + return new BitRate(left.Value * right, left.Unit); + } + + public static BitRate operator /(BitRate left, decimal right) + { + return new BitRate(left.Value / right, left.Unit); + } + + public static double operator /(BitRate left, BitRate right) + { + return left.BitsPerSecond / right.BitsPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(BitRate left, BitRate right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(BitRate left, BitRate right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(BitRate left, BitRate right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(BitRate left, BitRate 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs new file mode 100644 index 0000000000..167b27987d --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct BrakeSpecificFuelConsumption : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BrakeSpecificFuelConsumptionUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. + /// + public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; + + /// + /// 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 static QuantityType QuantityType => QuantityType.BrakeSpecificFuelConsumption; + + /// + /// All units of measurement for the BrakeSpecificFuelConsumption quantity. + /// + public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. + /// + public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(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 BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit 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(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. + /// + /// If value is NaN or Infinity. + public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) + { + double value = (double) gramsperkilowatthour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + } + /// + /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. + /// + /// If value is NaN or Infinity. + public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) + { + double value = (double) kilogramsperjoule; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + } + /// + /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. + /// + /// If value is NaN or Infinity. + public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) + { + 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. + public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) + { + return new BrakeSpecificFuelConsumption((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsumption result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 BrakeSpecificFuelConsumption result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 BrakeSpecificFuelConsumptionUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(-right.Value, right.Unit); + } + + public static BrakeSpecificFuelConsumption operator +(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static BrakeSpecificFuelConsumption operator *(double left, BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(left * right.Value, right.Unit); + } + + public static BrakeSpecificFuelConsumption operator *(BrakeSpecificFuelConsumption left, double right) + { + return new BrakeSpecificFuelConsumption(left.Value * right, left.Unit); + } + + public static BrakeSpecificFuelConsumption operator /(BrakeSpecificFuelConsumption left, double right) + { + return new BrakeSpecificFuelConsumption(left.Value / right, left.Unit); + } + + public static double operator /(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.KilogramsPerJoule / right.KilogramsPerJoule; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs new file mode 100644 index 0000000000..55ac3cd742 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Capacitance is the ability of a body to store an electric charge. + /// + /// + /// https://en.wikipedia.org/wiki/Capacitance + /// + public partial struct Capacitance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CapacitanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Capacitance, which is Farad. All conversions go via this value. + /// + public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Capacitance; + + /// + /// All units of measurement for the Capacitance quantity. + /// + public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Farad. + /// + public static Capacitance Zero => new Capacitance(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 CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Capacitance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Capacitance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Capacitance in Farads. + /// + public double Farads => As(CapacitanceUnit.Farad); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CapacitanceUnit 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(CapacitanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Capacitance from Farads. + /// + /// If value is NaN or Infinity. + public static Capacitance FromFarads(QuantityValue farads) + { + 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. + public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) + { + return new Capacitance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Capacitance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Capacitance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Capacitance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 CapacitanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out CapacitanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 CapacitanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Capacitance operator -(Capacitance right) + { + return new Capacitance(-right.Value, right.Unit); + } + + public static Capacitance operator +(Capacitance left, Capacitance right) + { + return new Capacitance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Capacitance operator -(Capacitance left, Capacitance right) + { + return new Capacitance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Capacitance operator *(double left, Capacitance right) + { + return new Capacitance(left * right.Value, right.Unit); + } + + public static Capacitance operator *(Capacitance left, double right) + { + return new Capacitance(left.Value * right, left.Unit); + } + + public static Capacitance operator /(Capacitance left, double right) + { + return new Capacitance(left.Value / right, left.Unit); + } + + public static double operator /(Capacitance left, Capacitance right) + { + return left.Farads / right.Farads; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Capacitance left, Capacitance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Capacitance left, Capacitance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Capacitance left, Capacitance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Capacitance left, Capacitance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs new file mode 100644 index 0000000000..d27cca70a7 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// A unit that represents a fractional change in size in response to a change in temperature. + /// + public partial struct CoefficientOfThermalExpansion : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CoefficientOfThermalExpansionUnit? _unit; + + static CoefficientOfThermalExpansion() + { + 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. + public CoefficientOfThermalExpansion(double numericValue, CoefficientOfThermalExpansionUnit unit) + { + if(unit == CoefficientOfThermalExpansionUnit.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 CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value. + /// + public static CoefficientOfThermalExpansionUnit BaseUnit => CoefficientOfThermalExpansionUnit.InverseKelvin; + + /// + /// Represents the largest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MaxValue => new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MinValue => new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.CoefficientOfThermalExpansion; + + /// + /// All units of measurement for the CoefficientOfThermalExpansion quantity. + /// + public static CoefficientOfThermalExpansionUnit[] Units { get; } = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. + /// + public static CoefficientOfThermalExpansion Zero => new CoefficientOfThermalExpansion(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 CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => CoefficientOfThermalExpansion.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeCelsius. + /// + public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeFahrenheit. + /// + public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + + /// + /// Get CoefficientOfThermalExpansion in InverseKelvin. + /// + public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit 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(CoefficientOfThermalExpansionUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityValue inversedegreecelsius) + { + double value = (double) inversedegreecelsius; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + } + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeFahrenheit. + /// + /// If value is NaN or Infinity. + public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(QuantityValue inversedegreefahrenheit) + { + double value = (double) inversedegreefahrenheit; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + } + /// + /// Get CoefficientOfThermalExpansion from InverseKelvin. + /// + /// If value is NaN or Infinity. + public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inversekelvin) + { + double value = (double) inversekelvin; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// CoefficientOfThermalExpansion unit value. + public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit) + { + return new CoefficientOfThermalExpansion((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} + /// + /// 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 CoefficientOfThermalExpansion Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 CoefficientOfThermalExpansion Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out CoefficientOfThermalExpansion result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 CoefficientOfThermalExpansion result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 CoefficientOfThermalExpansionUnit ParseUnit(string str) + { + return ParseUnit(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 CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 CoefficientOfThermalExpansionUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(-right.Value, right.Unit); + } + + public static CoefficientOfThermalExpansion operator +(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static CoefficientOfThermalExpansion operator *(double left, CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(left * right.Value, right.Unit); + } + + public static CoefficientOfThermalExpansion operator *(CoefficientOfThermalExpansion left, double right) + { + return new CoefficientOfThermalExpansion(left.Value * right, left.Unit); + } + + public static CoefficientOfThermalExpansion operator /(CoefficientOfThermalExpansion left, double right) + { + return new CoefficientOfThermalExpansion(left.Value / right, left.Unit); + } + + public static double operator /(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.InverseKelvin / right.InverseKelvin; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion 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 CoefficientOfThermalExpansion)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj)); + + return CompareTo((CoefficientOfThermalExpansion)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(CoefficientOfThermalExpansion other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + /// + /// + /// Compare equality to another CoefficientOfThermalExpansion 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(CoefficientOfThermalExpansion 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 CoefficientOfThermalExpansion. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . + /// + /// A CoefficientOfThermalExpansion with the specified unit. + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new CoefficientOfThermalExpansion(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 CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value*5/9; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue*9/5; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return 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(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs new file mode 100644 index 0000000000..79b9788d67 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs @@ -0,0 +1,1195 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. + /// + /// + /// http://en.wikipedia.org/wiki/Density + /// + public partial struct Density : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. + /// + public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Density; + + /// + /// All units of measurement for the Density quantity. + /// + public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// + public static Density Zero => new Density(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 DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Density.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Density.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DensityUnit 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(DensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Density from CentigramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) + { + double value = (double) centigramsperdeciliter; + return new Density(value, DensityUnit.CentigramPerDeciliter); + } + /// + /// Get Density from CentigramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) + { + double value = (double) centigramsperliter; + return new Density(value, DensityUnit.CentigramPerLiter); + } + /// + /// Get Density from CentigramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) + { + double value = (double) centigramspermilliliter; + return new Density(value, DensityUnit.CentigramPerMilliliter); + } + /// + /// Get Density from DecigramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) + { + double value = (double) decigramsperdeciliter; + return new Density(value, DensityUnit.DecigramPerDeciliter); + } + /// + /// Get Density from DecigramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) + { + double value = (double) decigramsperliter; + return new Density(value, DensityUnit.DecigramPerLiter); + } + /// + /// Get Density from DecigramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) + { + double value = (double) decigramspermilliliter; + return new Density(value, DensityUnit.DecigramPerMilliliter); + } + /// + /// Get Density from GramsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) + { + double value = (double) gramspercubiccentimeter; + return new Density(value, DensityUnit.GramPerCubicCentimeter); + } + /// + /// Get Density from GramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) + { + double value = (double) gramspercubicmeter; + return new Density(value, DensityUnit.GramPerCubicMeter); + } + /// + /// Get Density from GramsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) + { + double value = (double) gramspercubicmillimeter; + return new Density(value, DensityUnit.GramPerCubicMillimeter); + } + /// + /// Get Density from GramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) + { + double value = (double) gramsperdeciliter; + return new Density(value, DensityUnit.GramPerDeciliter); + } + /// + /// Get Density from GramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromGramsPerLiter(QuantityValue gramsperliter) + { + double value = (double) gramsperliter; + return new Density(value, DensityUnit.GramPerLiter); + } + /// + /// Get Density from GramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) + { + double value = (double) gramspermilliliter; + return new Density(value, DensityUnit.GramPerMilliliter); + } + /// + /// Get Density from KilogramsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) + { + double value = (double) kilogramspercubiccentimeter; + return new Density(value, DensityUnit.KilogramPerCubicCentimeter); + } + /// + /// Get Density from KilogramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) + { + double value = (double) kilogramspercubicmeter; + return new Density(value, DensityUnit.KilogramPerCubicMeter); + } + /// + /// Get Density from KilogramsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) + { + double value = (double) kilogramspercubicmillimeter; + return new Density(value, DensityUnit.KilogramPerCubicMillimeter); + } + /// + /// Get Density from KilopoundsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) + { + double value = (double) kilopoundspercubicfoot; + return new Density(value, DensityUnit.KilopoundPerCubicFoot); + } + /// + /// Get Density from KilopoundsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) + { + double value = (double) kilopoundspercubicinch; + return new Density(value, DensityUnit.KilopoundPerCubicInch); + } + /// + /// Get Density from MicrogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) + { + double value = (double) microgramsperdeciliter; + return new Density(value, DensityUnit.MicrogramPerDeciliter); + } + /// + /// Get Density from MicrogramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) + { + double value = (double) microgramsperliter; + return new Density(value, DensityUnit.MicrogramPerLiter); + } + /// + /// Get Density from MicrogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) + { + double value = (double) microgramspermilliliter; + return new Density(value, DensityUnit.MicrogramPerMilliliter); + } + /// + /// Get Density from MilligramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) + { + double value = (double) milligramspercubicmeter; + return new Density(value, DensityUnit.MilligramPerCubicMeter); + } + /// + /// Get Density from MilligramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) + { + double value = (double) milligramsperdeciliter; + return new Density(value, DensityUnit.MilligramPerDeciliter); + } + /// + /// Get Density from MilligramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) + { + double value = (double) milligramsperliter; + return new Density(value, DensityUnit.MilligramPerLiter); + } + /// + /// Get Density from MilligramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) + { + double value = (double) milligramspermilliliter; + return new Density(value, DensityUnit.MilligramPerMilliliter); + } + /// + /// Get Density from NanogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) + { + double value = (double) nanogramsperdeciliter; + return new Density(value, DensityUnit.NanogramPerDeciliter); + } + /// + /// Get Density from NanogramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) + { + double value = (double) nanogramsperliter; + return new Density(value, DensityUnit.NanogramPerLiter); + } + /// + /// Get Density from NanogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) + { + double value = (double) nanogramspermilliliter; + return new Density(value, DensityUnit.NanogramPerMilliliter); + } + /// + /// Get Density from PicogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) + { + double value = (double) picogramsperdeciliter; + return new Density(value, DensityUnit.PicogramPerDeciliter); + } + /// + /// Get Density from PicogramsPerLiter. + /// + /// If value is NaN or Infinity. + public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) + { + double value = (double) picogramsperliter; + return new Density(value, DensityUnit.PicogramPerLiter); + } + /// + /// Get Density from PicogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) + { + double value = (double) picogramspermilliliter; + return new Density(value, DensityUnit.PicogramPerMilliliter); + } + /// + /// Get Density from PoundsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) + { + double value = (double) poundspercubicfoot; + return new Density(value, DensityUnit.PoundPerCubicFoot); + } + /// + /// Get Density from PoundsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) + { + double value = (double) poundspercubicinch; + return new Density(value, DensityUnit.PoundPerCubicInch); + } + /// + /// Get Density from PoundsPerImperialGallon. + /// + /// If value is NaN or Infinity. + public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) + { + double value = (double) poundsperimperialgallon; + return new Density(value, DensityUnit.PoundPerImperialGallon); + } + /// + /// Get Density from PoundsPerUSGallon. + /// + /// If value is NaN or Infinity. + public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) + { + double value = (double) poundsperusgallon; + return new Density(value, DensityUnit.PoundPerUSGallon); + } + /// + /// Get Density from SlugsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) + { + double value = (double) slugspercubicfoot; + return new Density(value, DensityUnit.SlugPerCubicFoot); + } + /// + /// Get Density from TonnesPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) + { + double value = (double) tonnespercubiccentimeter; + return new Density(value, DensityUnit.TonnePerCubicCentimeter); + } + /// + /// Get Density from TonnesPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) + { + double value = (double) tonnespercubicmeter; + return new Density(value, DensityUnit.TonnePerCubicMeter); + } + /// + /// Get Density from TonnesPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) + { + 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. + public static Density From(QuantityValue value, DensityUnit fromUnit) + { + return new Density((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Density Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Density result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Density result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 DensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 DensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Density operator -(Density right) + { + return new Density(-right.Value, right.Unit); + } + + public static Density operator +(Density left, Density right) + { + return new Density(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Density operator -(Density left, Density right) + { + return new Density(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Density operator *(double left, Density right) + { + return new Density(left * right.Value, right.Unit); + } + + public static Density operator *(Density left, double right) + { + return new Density(left.Value * right, left.Unit); + } + + public static Density operator /(Density left, double right) + { + return new Density(left.Value / right, left.Unit); + } + + public static double operator /(Density left, Density right) + { + return left.KilogramsPerCubicMeter / right.KilogramsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Density left, Density right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Density left, Density right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Density left, Density right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Density left, Density 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs new file mode 100644 index 0000000000..9d60580fcb --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs @@ -0,0 +1,744 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Duration : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DurationUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Duration, which is Second. All conversions go via this value. + /// + public static DurationUnit BaseUnit => DurationUnit.Second; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Duration; + + /// + /// All units of measurement for the Duration quantity. + /// + public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// + public static Duration Zero => new Duration(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 DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Duration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Duration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DurationUnit 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(DurationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Duration from Days. + /// + /// If value is NaN or Infinity. + public static Duration FromDays(QuantityValue days) + { + double value = (double) days; + return new Duration(value, DurationUnit.Day); + } + /// + /// Get Duration from Hours. + /// + /// If value is NaN or Infinity. + public static Duration FromHours(QuantityValue hours) + { + double value = (double) hours; + return new Duration(value, DurationUnit.Hour); + } + /// + /// Get Duration from Microseconds. + /// + /// If value is NaN or Infinity. + public static Duration FromMicroseconds(QuantityValue microseconds) + { + double value = (double) microseconds; + return new Duration(value, DurationUnit.Microsecond); + } + /// + /// Get Duration from Milliseconds. + /// + /// If value is NaN or Infinity. + public static Duration FromMilliseconds(QuantityValue milliseconds) + { + double value = (double) milliseconds; + return new Duration(value, DurationUnit.Millisecond); + } + /// + /// Get Duration from Minutes. + /// + /// If value is NaN or Infinity. + public static Duration FromMinutes(QuantityValue minutes) + { + double value = (double) minutes; + return new Duration(value, DurationUnit.Minute); + } + /// + /// Get Duration from Months30. + /// + /// If value is NaN or Infinity. + public static Duration FromMonths30(QuantityValue months30) + { + double value = (double) months30; + return new Duration(value, DurationUnit.Month30); + } + /// + /// Get Duration from Nanoseconds. + /// + /// If value is NaN or Infinity. + public static Duration FromNanoseconds(QuantityValue nanoseconds) + { + double value = (double) nanoseconds; + return new Duration(value, DurationUnit.Nanosecond); + } + /// + /// Get Duration from Seconds. + /// + /// If value is NaN or Infinity. + public static Duration FromSeconds(QuantityValue seconds) + { + double value = (double) seconds; + return new Duration(value, DurationUnit.Second); + } + /// + /// Get Duration from Weeks. + /// + /// If value is NaN or Infinity. + public static Duration FromWeeks(QuantityValue weeks) + { + double value = (double) weeks; + return new Duration(value, DurationUnit.Week); + } + /// + /// Get Duration from Years365. + /// + /// If value is NaN or Infinity. + public static Duration FromYears365(QuantityValue years365) + { + 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. + public static Duration From(QuantityValue value, DurationUnit fromUnit) + { + return new Duration((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Duration Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Duration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Duration result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 DurationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DurationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 DurationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Duration operator -(Duration right) + { + return new Duration(-right.Value, right.Unit); + } + + public static Duration operator +(Duration left, Duration right) + { + return new Duration(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Duration operator -(Duration left, Duration right) + { + return new Duration(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Duration operator *(double left, Duration right) + { + return new Duration(left * right.Value, right.Unit); + } + + public static Duration operator *(Duration left, double right) + { + return new Duration(left.Value * right, left.Unit); + } + + public static Duration operator /(Duration left, double right) + { + return new Duration(left.Value / right, left.Unit); + } + + public static double operator /(Duration left, Duration right) + { + return left.Seconds / right.Seconds; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Duration left, Duration right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Duration left, Duration right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Duration left, Duration right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Duration left, Duration 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs new file mode 100644 index 0000000000..f92c2d2e61 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs @@ -0,0 +1,683 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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 + /// + /// + /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity + /// + public partial struct DynamicViscosity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DynamicViscosityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. + /// + public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; + + /// + /// 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 static QuantityType QuantityType => QuantityType.DynamicViscosity; + + /// + /// All units of measurement for the DynamicViscosity quantity. + /// + public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. + /// + public static DynamicViscosity Zero => new DynamicViscosity(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 DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => DynamicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DynamicViscosityUnit 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(DynamicViscosityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get DynamicViscosity from Centipoise. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromCentipoise(QuantityValue centipoise) + { + double value = (double) centipoise; + return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); + } + /// + /// Get DynamicViscosity from MicropascalSeconds. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) + { + double value = (double) micropascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); + } + /// + /// Get DynamicViscosity from MillipascalSeconds. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) + { + double value = (double) millipascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); + } + /// + /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) + { + double value = (double) newtonsecondspermetersquared; + return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); + } + /// + /// Get DynamicViscosity from PascalSeconds. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) + { + double value = (double) pascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); + } + /// + /// Get DynamicViscosity from Poise. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromPoise(QuantityValue poise) + { + 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. + public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) + { + return new DynamicViscosity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 DynamicViscosity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 DynamicViscosity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 DynamicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 DynamicViscosityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static DynamicViscosity operator -(DynamicViscosity right) + { + return new DynamicViscosity(-right.Value, right.Unit); + } + + public static DynamicViscosity operator +(DynamicViscosity left, DynamicViscosity right) + { + return new DynamicViscosity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static DynamicViscosity operator -(DynamicViscosity left, DynamicViscosity right) + { + return new DynamicViscosity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static DynamicViscosity operator *(double left, DynamicViscosity right) + { + return new DynamicViscosity(left * right.Value, right.Unit); + } + + public static DynamicViscosity operator *(DynamicViscosity left, double right) + { + return new DynamicViscosity(left.Value * right, left.Unit); + } + + public static DynamicViscosity operator /(DynamicViscosity left, double right) + { + return new DynamicViscosity(left.Value / right, left.Unit); + } + + public static double operator /(DynamicViscosity left, DynamicViscosity right) + { + return left.NewtonSecondsPerMeterSquared / right.NewtonSecondsPerMeterSquared; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(DynamicViscosity left, DynamicViscosity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(DynamicViscosity left, DynamicViscosity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(DynamicViscosity left, DynamicViscosity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(DynamicViscosity left, DynamicViscosity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs new file mode 100644 index 0000000000..56c568d5aa --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs @@ -0,0 +1,648 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct ElectricAdmittance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricAdmittanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. + /// + public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricAdmittance; + + /// + /// All units of measurement for the ElectricAdmittance quantity. + /// + public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricAdmittance Zero => new ElectricAdmittance(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 ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricAdmittance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricAdmittanceUnit 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(ElectricAdmittanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricAdmittance from Microsiemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) + { + double value = (double) microsiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); + } + /// + /// Get ElectricAdmittance from Millisiemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) + { + double value = (double) millisiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); + } + /// + /// Get ElectricAdmittance from Nanosiemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) + { + double value = (double) nanosiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); + } + /// + /// Get ElectricAdmittance from Siemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromSiemens(QuantityValue siemens) + { + 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. + public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) + { + return new ElectricAdmittance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricAdmittance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricAdmittance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricAdmittance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricAdmittanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricAdmittance operator -(ElectricAdmittance right) + { + return new ElectricAdmittance(-right.Value, right.Unit); + } + + public static ElectricAdmittance operator +(ElectricAdmittance left, ElectricAdmittance right) + { + return new ElectricAdmittance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricAdmittance operator -(ElectricAdmittance left, ElectricAdmittance right) + { + return new ElectricAdmittance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricAdmittance operator *(double left, ElectricAdmittance right) + { + return new ElectricAdmittance(left * right.Value, right.Unit); + } + + public static ElectricAdmittance operator *(ElectricAdmittance left, double right) + { + return new ElectricAdmittance(left.Value * right, left.Unit); + } + + public static ElectricAdmittance operator /(ElectricAdmittance left, double right) + { + return new ElectricAdmittance(left.Value / right, left.Unit); + } + + public static double operator /(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Siemens / right.Siemens; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricAdmittance left, ElectricAdmittance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs new file mode 100644 index 0000000000..14b5a81345 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electric_charge + /// + public partial struct ElectricCharge : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. + /// + public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCharge; + + /// + /// All units of measurement for the ElectricCharge quantity. + /// + public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. + /// + public static ElectricCharge Zero => new ElectricCharge(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 ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCharge.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCharge in Coulombs. + /// + public double Coulombs => As(ElectricChargeUnit.Coulomb); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeUnit 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(ElectricChargeUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCharge from Coulombs. + /// + /// If value is NaN or Infinity. + public static ElectricCharge FromCoulombs(QuantityValue coulombs) + { + 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. + public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) + { + return new ElectricCharge((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCharge Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCharge result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCharge result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricChargeUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricChargeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricChargeUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricCharge operator -(ElectricCharge right) + { + return new ElectricCharge(-right.Value, right.Unit); + } + + public static ElectricCharge operator +(ElectricCharge left, ElectricCharge right) + { + return new ElectricCharge(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCharge operator -(ElectricCharge left, ElectricCharge right) + { + return new ElectricCharge(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCharge operator *(double left, ElectricCharge right) + { + return new ElectricCharge(left * right.Value, right.Unit); + } + + public static ElectricCharge operator *(ElectricCharge left, double right) + { + return new ElectricCharge(left.Value * right, left.Unit); + } + + public static ElectricCharge operator /(ElectricCharge left, double right) + { + return new ElectricCharge(left.Value / right, left.Unit); + } + + public static double operator /(ElectricCharge left, ElectricCharge right) + { + return left.Coulombs / right.Coulombs; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricCharge left, ElectricCharge right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricCharge left, ElectricCharge right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricCharge left, ElectricCharge right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricCharge left, ElectricCharge 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs new file mode 100644 index 0000000000..0a16178af6 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Charge_density + /// + public partial struct ElectricChargeDensity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeDensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. + /// + public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricChargeDensity; + + /// + /// All units of measurement for the ElectricChargeDensity quantity. + /// + public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. + /// + public static ElectricChargeDensity Zero => new ElectricChargeDensity(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 ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricChargeDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricChargeDensity in CoulombsPerCubicMeter. + /// + public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeDensityUnit 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(ElectricChargeDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricChargeDensity from CoulombsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) + { + 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. + public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) + { + return new ElectricChargeDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricChargeDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricChargeDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricChargeDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricChargeDensity operator -(ElectricChargeDensity right) + { + return new ElectricChargeDensity(-right.Value, right.Unit); + } + + public static ElectricChargeDensity operator +(ElectricChargeDensity left, ElectricChargeDensity right) + { + return new ElectricChargeDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricChargeDensity operator -(ElectricChargeDensity left, ElectricChargeDensity right) + { + return new ElectricChargeDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricChargeDensity operator *(double left, ElectricChargeDensity right) + { + return new ElectricChargeDensity(left * right.Value, right.Unit); + } + + public static ElectricChargeDensity operator *(ElectricChargeDensity left, double right) + { + return new ElectricChargeDensity(left.Value * right, left.Unit); + } + + public static ElectricChargeDensity operator /(ElectricChargeDensity left, double right) + { + return new ElectricChargeDensity(left.Value / right, left.Unit); + } + + public static double operator /(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.CoulombsPerCubicMeter / right.CoulombsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricChargeDensity left, ElectricChargeDensity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs new file mode 100644 index 0000000000..cf63700d7a --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs @@ -0,0 +1,635 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance + /// + public partial struct ElectricConductance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. + /// + public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricConductance; + + /// + /// All units of measurement for the ElectricConductance quantity. + /// + public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricConductance Zero => new ElectricConductance(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 ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductanceUnit 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(ElectricConductanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricConductance from Microsiemens. + /// + /// If value is NaN or Infinity. + public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) + { + double value = (double) microsiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); + } + /// + /// Get ElectricConductance from Millisiemens. + /// + /// If value is NaN or Infinity. + public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) + { + double value = (double) millisiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); + } + /// + /// Get ElectricConductance from Siemens. + /// + /// If value is NaN or Infinity. + public static ElectricConductance FromSiemens(QuantityValue siemens) + { + 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. + public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) + { + return new ElectricConductance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricConductance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricConductance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricConductance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricConductanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricConductanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricConductance operator -(ElectricConductance right) + { + return new ElectricConductance(-right.Value, right.Unit); + } + + public static ElectricConductance operator +(ElectricConductance left, ElectricConductance right) + { + return new ElectricConductance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricConductance operator -(ElectricConductance left, ElectricConductance right) + { + return new ElectricConductance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricConductance operator *(double left, ElectricConductance right) + { + return new ElectricConductance(left * right.Value, right.Unit); + } + + public static ElectricConductance operator *(ElectricConductance left, double right) + { + return new ElectricConductance(left.Value * right, left.Unit); + } + + public static ElectricConductance operator /(ElectricConductance left, double right) + { + return new ElectricConductance(left.Value / right, left.Unit); + } + + public static double operator /(ElectricConductance left, ElectricConductance right) + { + return left.Siemens / right.Siemens; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricConductance left, ElectricConductance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricConductance left, ElectricConductance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricConductance left, ElectricConductance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricConductance left, ElectricConductance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs new file mode 100644 index 0000000000..07b04d69e2 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// + public partial struct ElectricConductivity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductivityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. + /// + public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricConductivity; + + /// + /// All units of measurement for the ElectricConductivity quantity. + /// + public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. + /// + public static ElectricConductivity Zero => new ElectricConductivity(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 ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricConductivity in SiemensPerMeter. + /// + public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductivityUnit 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(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricConductivity from SiemensPerMeter. + /// + /// If value is NaN or Infinity. + public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) + { + 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. + public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) + { + return new ElectricConductivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricConductivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricConductivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricConductivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricConductivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricConductivity operator -(ElectricConductivity right) + { + return new ElectricConductivity(-right.Value, right.Unit); + } + + public static ElectricConductivity operator +(ElectricConductivity left, ElectricConductivity right) + { + return new ElectricConductivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricConductivity operator -(ElectricConductivity left, ElectricConductivity right) + { + return new ElectricConductivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricConductivity operator *(double left, ElectricConductivity right) + { + return new ElectricConductivity(left * right.Value, right.Unit); + } + + public static ElectricConductivity operator *(ElectricConductivity left, double right) + { + return new ElectricConductivity(left.Value * right, left.Unit); + } + + public static ElectricConductivity operator /(ElectricConductivity left, double right) + { + return new ElectricConductivity(left.Value / right, left.Unit); + } + + public static double operator /(ElectricConductivity left, ElectricConductivity right) + { + return left.SiemensPerMeter / right.SiemensPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricConductivity left, ElectricConductivity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricConductivity left, ElectricConductivity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricConductivity left, ElectricConductivity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricConductivity left, ElectricConductivity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs new file mode 100644 index 0000000000..546bca6c60 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs @@ -0,0 +1,712 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ElectricCurrent : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. + /// + public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCurrent; + + /// + /// All units of measurement for the ElectricCurrent quantity. + /// + public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. + /// + public static ElectricCurrent Zero => new ElectricCurrent(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 ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrent.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentUnit 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(ElectricCurrentUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrent from Amperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromAmperes(QuantityValue amperes) + { + double value = (double) amperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); + } + /// + /// Get ElectricCurrent from Centiamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) + { + double value = (double) centiamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); + } + /// + /// Get ElectricCurrent from Kiloamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) + { + double value = (double) kiloamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); + } + /// + /// Get ElectricCurrent from Megaamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) + { + double value = (double) megaamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); + } + /// + /// Get ElectricCurrent from Microamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) + { + double value = (double) microamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); + } + /// + /// Get ElectricCurrent from Milliamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) + { + double value = (double) milliamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); + } + /// + /// Get ElectricCurrent from Nanoamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) + { + double value = (double) nanoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); + } + /// + /// Get ElectricCurrent from Picoamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) + { + 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. + public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) + { + return new ElectricCurrent((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCurrent Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCurrent result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricCurrentUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricCurrentUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricCurrent operator -(ElectricCurrent right) + { + return new ElectricCurrent(-right.Value, right.Unit); + } + + public static ElectricCurrent operator +(ElectricCurrent left, ElectricCurrent right) + { + return new ElectricCurrent(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCurrent operator -(ElectricCurrent left, ElectricCurrent right) + { + return new ElectricCurrent(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCurrent operator *(double left, ElectricCurrent right) + { + return new ElectricCurrent(left * right.Value, right.Unit); + } + + public static ElectricCurrent operator *(ElectricCurrent left, double right) + { + return new ElectricCurrent(left.Value * right, left.Unit); + } + + public static ElectricCurrent operator /(ElectricCurrent left, double right) + { + return new ElectricCurrent(left.Value / right, left.Unit); + } + + public static double operator /(ElectricCurrent left, ElectricCurrent right) + { + return left.Amperes / right.Amperes; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricCurrent left, ElectricCurrent right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricCurrent left, ElectricCurrent right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricCurrent left, ElectricCurrent right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricCurrent left, ElectricCurrent 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs new file mode 100644 index 0000000000..59306fe6ac --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In electromagnetism, current density is the electric current per unit area of cross section. + /// + /// + /// https://en.wikipedia.org/wiki/Current_density + /// + public partial struct ElectricCurrentDensity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentDensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. + /// + public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCurrentDensity; + + /// + /// All units of measurement for the ElectricCurrentDensity quantity. + /// + public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. + /// + public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(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 ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentDensity in AmperesPerSquareMeter. + /// + public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentDensityUnit 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(ElectricCurrentDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrentDensity from AmperesPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) + { + 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. + public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) + { + return new ElectricCurrentDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricCurrentDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricCurrentDensity operator -(ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(-right.Value, right.Unit); + } + + public static ElectricCurrentDensity operator +(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCurrentDensity operator -(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCurrentDensity operator *(double left, ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(left * right.Value, right.Unit); + } + + public static ElectricCurrentDensity operator *(ElectricCurrentDensity left, double right) + { + return new ElectricCurrentDensity(left.Value * right, left.Unit); + } + + public static ElectricCurrentDensity operator /(ElectricCurrentDensity left, double right) + { + return new ElectricCurrentDensity(left.Value / right, left.Unit); + } + + public static double operator /(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.AmperesPerSquareMeter / right.AmperesPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricCurrentDensity left, ElectricCurrentDensity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs new file mode 100644 index 0000000000..8a71720550 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs @@ -0,0 +1,600 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In electromagnetism, the current gradient describes how the current changes in time. + /// + public partial struct ElectricCurrentGradient : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentGradientUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. + /// + public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricCurrentGradient; + + /// + /// All units of measurement for the ElectricCurrentGradient quantity. + /// + public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. + /// + public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(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 ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentGradient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentGradient in AmperesPerSecond. + /// + public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentGradientUnit 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(ElectricCurrentGradientUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrentGradient from AmperesPerSecond. + /// + /// If value is NaN or Infinity. + public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) + { + 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. + public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) + { + return new ElectricCurrentGradient((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentGradient Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricCurrentGradient result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricCurrentGradientUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricCurrentGradient operator -(ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(-right.Value, right.Unit); + } + + public static ElectricCurrentGradient operator +(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCurrentGradient operator -(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricCurrentGradient operator *(double left, ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(left * right.Value, right.Unit); + } + + public static ElectricCurrentGradient operator *(ElectricCurrentGradient left, double right) + { + return new ElectricCurrentGradient(left.Value * right, left.Unit); + } + + public static ElectricCurrentGradient operator /(ElectricCurrentGradient left, double right) + { + return new ElectricCurrentGradient(left.Value / right, left.Unit); + } + + public static double operator /(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.AmperesPerSecond / right.AmperesPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricCurrentGradient left, ElectricCurrentGradient 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs new file mode 100644 index 0000000000..1abc713686 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. + /// + /// + /// https://en.wikipedia.org/wiki/Electric_field + /// + public partial struct ElectricField : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricFieldUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. + /// + public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricField; + + /// + /// All units of measurement for the ElectricField quantity. + /// + public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. + /// + public static ElectricField Zero => new ElectricField(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 ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricField in VoltsPerMeter. + /// + public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricFieldUnit 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(ElectricFieldUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricField from VoltsPerMeter. + /// + /// If value is NaN or Infinity. + public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) + { + 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. + public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) + { + return new ElectricField((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricField Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricField result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricField result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricFieldUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricFieldUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricField operator -(ElectricField right) + { + return new ElectricField(-right.Value, right.Unit); + } + + public static ElectricField operator +(ElectricField left, ElectricField right) + { + return new ElectricField(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricField operator -(ElectricField left, ElectricField right) + { + return new ElectricField(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricField operator *(double left, ElectricField right) + { + return new ElectricField(left * right.Value, right.Unit); + } + + public static ElectricField operator *(ElectricField left, double right) + { + return new ElectricField(left.Value * right, left.Unit); + } + + public static ElectricField operator /(ElectricField left, double right) + { + return new ElectricField(left.Value / right, left.Unit); + } + + public static double operator /(ElectricField left, ElectricField right) + { + return left.VoltsPerMeter / right.VoltsPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricField left, ElectricField right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricField left, ElectricField right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricField left, ElectricField right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricField left, ElectricField 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs new file mode 100644 index 0000000000..c7c7f24382 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Inductance is a property of an electrical conductor which opposes a change in current. + /// + /// + /// https://en.wikipedia.org/wiki/Inductance + /// + public partial struct ElectricInductance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricInductanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. + /// + public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricInductance; + + /// + /// All units of measurement for the ElectricInductance quantity. + /// + public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Henry. + /// + public static ElectricInductance Zero => new ElectricInductance(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 ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricInductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricInductance in Henries. + /// + public double Henries => As(ElectricInductanceUnit.Henry); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricInductanceUnit 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(ElectricInductanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricInductance from Henries. + /// + /// If value is NaN or Infinity. + public static ElectricInductance FromHenries(QuantityValue henries) + { + 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. + public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) + { + return new ElectricInductance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricInductance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricInductance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricInductance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricInductanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricInductanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricInductance operator -(ElectricInductance right) + { + return new ElectricInductance(-right.Value, right.Unit); + } + + public static ElectricInductance operator +(ElectricInductance left, ElectricInductance right) + { + return new ElectricInductance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricInductance operator -(ElectricInductance left, ElectricInductance right) + { + return new ElectricInductance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricInductance operator *(double left, ElectricInductance right) + { + return new ElectricInductance(left * right.Value, right.Unit); + } + + public static ElectricInductance operator *(ElectricInductance left, double right) + { + return new ElectricInductance(left.Value * right, left.Unit); + } + + public static ElectricInductance operator /(ElectricInductance left, double right) + { + return new ElectricInductance(left.Value / right, left.Unit); + } + + public static double operator /(ElectricInductance left, ElectricInductance right) + { + return left.Henries / right.Henries; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricInductance left, ElectricInductance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricInductance left, ElectricInductance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricInductance left, ElectricInductance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricInductance left, ElectricInductance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs new file mode 100644 index 0000000000..b28667c840 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs @@ -0,0 +1,664 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ElectricPotential : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. + /// + public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricPotential; + + /// + /// All units of measurement for the ElectricPotential quantity. + /// + public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Volt. + /// + public static ElectricPotential Zero => new ElectricPotential(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 ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotential.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialUnit 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(ElectricPotentialUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotential from Kilovolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromKilovolts(QuantityValue kilovolts) + { + double value = (double) kilovolts; + return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); + } + /// + /// Get ElectricPotential from Megavolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromMegavolts(QuantityValue megavolts) + { + double value = (double) megavolts; + return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); + } + /// + /// Get ElectricPotential from Microvolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromMicrovolts(QuantityValue microvolts) + { + double value = (double) microvolts; + return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); + } + /// + /// Get ElectricPotential from Millivolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromMillivolts(QuantityValue millivolts) + { + double value = (double) millivolts; + return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); + } + /// + /// Get ElectricPotential from Volts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromVolts(QuantityValue volts) + { + 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. + public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) + { + return new ElectricPotential((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricPotential Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotential result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricPotential result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricPotentialUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricPotentialUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricPotential operator -(ElectricPotential right) + { + return new ElectricPotential(-right.Value, right.Unit); + } + + public static ElectricPotential operator +(ElectricPotential left, ElectricPotential right) + { + return new ElectricPotential(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricPotential operator -(ElectricPotential left, ElectricPotential right) + { + return new ElectricPotential(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricPotential operator *(double left, ElectricPotential right) + { + return new ElectricPotential(left * right.Value, right.Unit); + } + + public static ElectricPotential operator *(ElectricPotential left, double right) + { + return new ElectricPotential(left.Value * right, left.Unit); + } + + public static ElectricPotential operator /(ElectricPotential left, double right) + { + return new ElectricPotential(left.Value / right, left.Unit); + } + + public static double operator /(ElectricPotential left, ElectricPotential right) + { + return left.Volts / right.Volts; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricPotential left, ElectricPotential right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricPotential left, ElectricPotential right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricPotential left, ElectricPotential right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricPotential left, ElectricPotential 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs new file mode 100644 index 0000000000..a172668d60 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs @@ -0,0 +1,664 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The Electric Potential of a system known to use Alternating Current. + /// + public partial struct ElectricPotentialAc : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialAcUnit? _unit; + + static ElectricPotentialAc() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. + /// + public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricPotentialAc; + + /// + /// All units of measurement for the ElectricPotentialAc quantity. + /// + public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. + /// + public static ElectricPotentialAc Zero => new ElectricPotentialAc(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 ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialAc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialAcUnit 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(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialAc from KilovoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) + { + double value = (double) kilovoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); + } + /// + /// Get ElectricPotentialAc from MegavoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) + { + double value = (double) megavoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); + } + /// + /// Get ElectricPotentialAc from MicrovoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) + { + double value = (double) microvoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); + } + /// + /// Get ElectricPotentialAc from MillivoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) + { + double value = (double) millivoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); + } + /// + /// Get ElectricPotentialAc from VoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) + { + 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. + public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) + { + return new ElectricPotentialAc((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialAc Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialAc result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricPotentialAcUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricPotentialAc operator -(ElectricPotentialAc right) + { + return new ElectricPotentialAc(-right.Value, right.Unit); + } + + public static ElectricPotentialAc operator +(ElectricPotentialAc left, ElectricPotentialAc right) + { + return new ElectricPotentialAc(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricPotentialAc operator -(ElectricPotentialAc left, ElectricPotentialAc right) + { + return new ElectricPotentialAc(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricPotentialAc operator *(double left, ElectricPotentialAc right) + { + return new ElectricPotentialAc(left * right.Value, right.Unit); + } + + public static ElectricPotentialAc operator *(ElectricPotentialAc left, double right) + { + return new ElectricPotentialAc(left.Value * right, left.Unit); + } + + public static ElectricPotentialAc operator /(ElectricPotentialAc left, double right) + { + return new ElectricPotentialAc(left.Value / right, left.Unit); + } + + public static double operator /(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.VoltsAc / right.VoltsAc; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricPotentialAc left, ElectricPotentialAc 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs new file mode 100644 index 0000000000..8f1cf03d97 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs @@ -0,0 +1,664 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The Electric Potential of a system known to use Direct Current. + /// + public partial struct ElectricPotentialDc : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialDcUnit? _unit; + + static ElectricPotentialDc() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. + /// + public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricPotentialDc; + + /// + /// All units of measurement for the ElectricPotentialDc quantity. + /// + public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. + /// + public static ElectricPotentialDc Zero => new ElectricPotentialDc(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 ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialDc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialDcUnit 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(ElectricPotentialDcUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialDc from KilovoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) + { + double value = (double) kilovoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); + } + /// + /// Get ElectricPotentialDc from MegavoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) + { + double value = (double) megavoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); + } + /// + /// Get ElectricPotentialDc from MicrovoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) + { + double value = (double) microvoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); + } + /// + /// Get ElectricPotentialDc from MillivoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) + { + double value = (double) millivoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); + } + /// + /// Get ElectricPotentialDc from VoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) + { + 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. + public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) + { + return new ElectricPotentialDc((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialDc Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricPotentialDc result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricPotentialDcUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricPotentialDc operator -(ElectricPotentialDc right) + { + return new ElectricPotentialDc(-right.Value, right.Unit); + } + + public static ElectricPotentialDc operator +(ElectricPotentialDc left, ElectricPotentialDc right) + { + return new ElectricPotentialDc(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricPotentialDc operator -(ElectricPotentialDc left, ElectricPotentialDc right) + { + return new ElectricPotentialDc(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricPotentialDc operator *(double left, ElectricPotentialDc right) + { + return new ElectricPotentialDc(left * right.Value, right.Unit); + } + + public static ElectricPotentialDc operator *(ElectricPotentialDc left, double right) + { + return new ElectricPotentialDc(left.Value * right, left.Unit); + } + + public static ElectricPotentialDc operator /(ElectricPotentialDc left, double right) + { + return new ElectricPotentialDc(left.Value / right, left.Unit); + } + + public static double operator /(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.VoltsDc / right.VoltsDc; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricPotentialDc left, ElectricPotentialDc 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs new file mode 100644 index 0000000000..f70db6dcc1 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs @@ -0,0 +1,648 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ElectricResistance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. + /// + public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricResistance; + + /// + /// All units of measurement for the ElectricResistance quantity. + /// + public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. + /// + public static ElectricResistance Zero => new ElectricResistance(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 ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistanceUnit 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(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistance from Kiloohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromKiloohms(QuantityValue kiloohms) + { + double value = (double) kiloohms; + return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); + } + /// + /// Get ElectricResistance from Megaohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromMegaohms(QuantityValue megaohms) + { + double value = (double) megaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); + } + /// + /// Get ElectricResistance from Milliohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromMilliohms(QuantityValue milliohms) + { + double value = (double) milliohms; + return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); + } + /// + /// Get ElectricResistance from Ohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromOhms(QuantityValue ohms) + { + 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. + public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) + { + return new ElectricResistance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricResistance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricResistance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricResistance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricResistanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricResistance operator -(ElectricResistance right) + { + return new ElectricResistance(-right.Value, right.Unit); + } + + public static ElectricResistance operator +(ElectricResistance left, ElectricResistance right) + { + return new ElectricResistance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricResistance operator -(ElectricResistance left, ElectricResistance right) + { + return new ElectricResistance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricResistance operator *(double left, ElectricResistance right) + { + return new ElectricResistance(left * right.Value, right.Unit); + } + + public static ElectricResistance operator *(ElectricResistance left, double right) + { + return new ElectricResistance(left.Value * right, left.Unit); + } + + public static ElectricResistance operator /(ElectricResistance left, double right) + { + return new ElectricResistance(left.Value / right, left.Unit); + } + + public static double operator /(ElectricResistance left, ElectricResistance right) + { + return left.Ohms / right.Ohms; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricResistance left, ElectricResistance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricResistance left, ElectricResistance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricResistance left, ElectricResistance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricResistance left, ElectricResistance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs new file mode 100644 index 0000000000..4233c05f13 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs @@ -0,0 +1,651 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// + public partial struct ElectricResistivity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistivityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. + /// + public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ElectricResistivity; + + /// + /// All units of measurement for the ElectricResistivity quantity. + /// + public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. + /// + public static ElectricResistivity Zero => new ElectricResistivity(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 ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistivityUnit 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(ElectricResistivityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistivity from MicroohmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) + { + double value = (double) microohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); + } + /// + /// Get ElectricResistivity from MilliohmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) + { + double value = (double) milliohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); + } + /// + /// Get ElectricResistivity from NanoohmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) + { + double value = (double) nanoohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); + } + /// + /// Get ElectricResistivity from OhmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) + { + 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. + public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) + { + return new ElectricResistivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ElectricResistivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricResistivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ElectricResistivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ElectricResistivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ElectricResistivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ElectricResistivity operator -(ElectricResistivity right) + { + return new ElectricResistivity(-right.Value, right.Unit); + } + + public static ElectricResistivity operator +(ElectricResistivity left, ElectricResistivity right) + { + return new ElectricResistivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricResistivity operator -(ElectricResistivity left, ElectricResistivity right) + { + return new ElectricResistivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ElectricResistivity operator *(double left, ElectricResistivity right) + { + return new ElectricResistivity(left * right.Value, right.Unit); + } + + public static ElectricResistivity operator *(ElectricResistivity left, double right) + { + return new ElectricResistivity(left.Value * right, left.Unit); + } + + public static ElectricResistivity operator /(ElectricResistivity left, double right) + { + return new ElectricResistivity(left.Value / right, left.Unit); + } + + public static double operator /(ElectricResistivity left, ElectricResistivity right) + { + return left.OhmMeters / right.OhmMeters; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ElectricResistivity left, ElectricResistivity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ElectricResistivity left, ElectricResistivity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ElectricResistivity left, ElectricResistivity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ElectricResistivity left, ElectricResistivity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs new file mode 100644 index 0000000000..7feddd4041 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs @@ -0,0 +1,936 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Energy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly EnergyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Energy, which is Joule. All conversions go via this value. + /// + public static EnergyUnit BaseUnit => EnergyUnit.Joule; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Energy; + + /// + /// All units of measurement for the Energy quantity. + /// + public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Joule. + /// + public static Energy Zero => new Energy(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 EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Energy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Energy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EnergyUnit 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(EnergyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Energy from BritishThermalUnits. + /// + /// If value is NaN or Infinity. + public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) + { + double value = (double) britishthermalunits; + return new Energy(value, EnergyUnit.BritishThermalUnit); + } + /// + /// Get Energy from Calories. + /// + /// If value is NaN or Infinity. + public static Energy FromCalories(QuantityValue calories) + { + double value = (double) calories; + return new Energy(value, EnergyUnit.Calorie); + } + /// + /// Get Energy from DecathermsEc. + /// + /// If value is NaN or Infinity. + public static Energy FromDecathermsEc(QuantityValue decathermsec) + { + double value = (double) decathermsec; + return new Energy(value, EnergyUnit.DecathermEc); + } + /// + /// Get Energy from DecathermsImperial. + /// + /// If value is NaN or Infinity. + public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) + { + double value = (double) decathermsimperial; + return new Energy(value, EnergyUnit.DecathermImperial); + } + /// + /// Get Energy from DecathermsUs. + /// + /// If value is NaN or Infinity. + public static Energy FromDecathermsUs(QuantityValue decathermsus) + { + double value = (double) decathermsus; + return new Energy(value, EnergyUnit.DecathermUs); + } + /// + /// Get Energy from ElectronVolts. + /// + /// If value is NaN or Infinity. + public static Energy FromElectronVolts(QuantityValue electronvolts) + { + double value = (double) electronvolts; + return new Energy(value, EnergyUnit.ElectronVolt); + } + /// + /// Get Energy from Ergs. + /// + /// If value is NaN or Infinity. + public static Energy FromErgs(QuantityValue ergs) + { + double value = (double) ergs; + return new Energy(value, EnergyUnit.Erg); + } + /// + /// Get Energy from FootPounds. + /// + /// If value is NaN or Infinity. + public static Energy FromFootPounds(QuantityValue footpounds) + { + double value = (double) footpounds; + return new Energy(value, EnergyUnit.FootPound); + } + /// + /// Get Energy from GigabritishThermalUnits. + /// + /// If value is NaN or Infinity. + public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) + { + double value = (double) gigabritishthermalunits; + return new Energy(value, EnergyUnit.GigabritishThermalUnit); + } + /// + /// Get Energy from GigawattHours. + /// + /// If value is NaN or Infinity. + public static Energy FromGigawattHours(QuantityValue gigawatthours) + { + double value = (double) gigawatthours; + return new Energy(value, EnergyUnit.GigawattHour); + } + /// + /// Get Energy from Joules. + /// + /// If value is NaN or Infinity. + public static Energy FromJoules(QuantityValue joules) + { + double value = (double) joules; + return new Energy(value, EnergyUnit.Joule); + } + /// + /// Get Energy from KilobritishThermalUnits. + /// + /// If value is NaN or Infinity. + public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) + { + double value = (double) kilobritishthermalunits; + return new Energy(value, EnergyUnit.KilobritishThermalUnit); + } + /// + /// Get Energy from Kilocalories. + /// + /// If value is NaN or Infinity. + public static Energy FromKilocalories(QuantityValue kilocalories) + { + double value = (double) kilocalories; + return new Energy(value, EnergyUnit.Kilocalorie); + } + /// + /// Get Energy from Kilojoules. + /// + /// If value is NaN or Infinity. + public static Energy FromKilojoules(QuantityValue kilojoules) + { + double value = (double) kilojoules; + return new Energy(value, EnergyUnit.Kilojoule); + } + /// + /// Get Energy from KilowattHours. + /// + /// If value is NaN or Infinity. + public static Energy FromKilowattHours(QuantityValue kilowatthours) + { + double value = (double) kilowatthours; + return new Energy(value, EnergyUnit.KilowattHour); + } + /// + /// Get Energy from MegabritishThermalUnits. + /// + /// If value is NaN or Infinity. + public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) + { + double value = (double) megabritishthermalunits; + return new Energy(value, EnergyUnit.MegabritishThermalUnit); + } + /// + /// Get Energy from Megajoules. + /// + /// If value is NaN or Infinity. + public static Energy FromMegajoules(QuantityValue megajoules) + { + double value = (double) megajoules; + return new Energy(value, EnergyUnit.Megajoule); + } + /// + /// Get Energy from MegawattHours. + /// + /// If value is NaN or Infinity. + public static Energy FromMegawattHours(QuantityValue megawatthours) + { + double value = (double) megawatthours; + return new Energy(value, EnergyUnit.MegawattHour); + } + /// + /// Get Energy from ThermsEc. + /// + /// If value is NaN or Infinity. + public static Energy FromThermsEc(QuantityValue thermsec) + { + double value = (double) thermsec; + return new Energy(value, EnergyUnit.ThermEc); + } + /// + /// Get Energy from ThermsImperial. + /// + /// If value is NaN or Infinity. + public static Energy FromThermsImperial(QuantityValue thermsimperial) + { + double value = (double) thermsimperial; + return new Energy(value, EnergyUnit.ThermImperial); + } + /// + /// Get Energy from ThermsUs. + /// + /// If value is NaN or Infinity. + public static Energy FromThermsUs(QuantityValue thermsus) + { + double value = (double) thermsus; + return new Energy(value, EnergyUnit.ThermUs); + } + /// + /// Get Energy from WattHours. + /// + /// If value is NaN or Infinity. + public static Energy FromWattHours(QuantityValue watthours) + { + 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. + public static Energy From(QuantityValue value, EnergyUnit fromUnit) + { + return new Energy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Energy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Energy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Energy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 EnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out EnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 EnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Energy operator -(Energy right) + { + return new Energy(-right.Value, right.Unit); + } + + public static Energy operator +(Energy left, Energy right) + { + return new Energy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Energy operator -(Energy left, Energy right) + { + return new Energy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Energy operator *(double left, Energy right) + { + return new Energy(left * right.Value, right.Unit); + } + + public static Energy operator *(Energy left, double right) + { + return new Energy(left.Value * right, left.Unit); + } + + public static Energy operator /(Energy left, double right) + { + return new Energy(left.Value / right, left.Unit); + } + + public static double operator /(Energy left, Energy right) + { + return left.Joules / right.Joules; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Energy left, Energy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Energy left, Energy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Energy left, Energy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Energy left, Energy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs new file mode 100644 index 0000000000..efa316a1f4 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs @@ -0,0 +1,696 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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 + /// + public partial struct Entropy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly EntropyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. + /// + public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Entropy; + + /// + /// All units of measurement for the Entropy quantity. + /// + public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. + /// + public static Entropy Zero => new Entropy(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 EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Entropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Entropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EntropyUnit 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(EntropyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Entropy from CaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) + { + double value = (double) caloriesperkelvin; + return new Entropy(value, EntropyUnit.CaloriePerKelvin); + } + /// + /// Get Entropy from JoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) + { + double value = (double) joulesperdegreecelsius; + return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); + } + /// + /// Get Entropy from JoulesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) + { + double value = (double) joulesperkelvin; + return new Entropy(value, EntropyUnit.JoulePerKelvin); + } + /// + /// Get Entropy from KilocaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) + { + double value = (double) kilocaloriesperkelvin; + return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); + } + /// + /// Get Entropy from KilojoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) + { + double value = (double) kilojoulesperdegreecelsius; + return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); + } + /// + /// Get Entropy from KilojoulesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) + { + double value = (double) kilojoulesperkelvin; + return new Entropy(value, EntropyUnit.KilojoulePerKelvin); + } + /// + /// Get Entropy from MegajoulesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) + { + 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. + public static Entropy From(QuantityValue value, EntropyUnit fromUnit) + { + return new Entropy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Entropy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Entropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Entropy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 EntropyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out EntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 EntropyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Entropy operator -(Entropy right) + { + return new Entropy(-right.Value, right.Unit); + } + + public static Entropy operator +(Entropy left, Entropy right) + { + return new Entropy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Entropy operator -(Entropy left, Entropy right) + { + return new Entropy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Entropy operator *(double left, Entropy right) + { + return new Entropy(left * right.Value, right.Unit); + } + + public static Entropy operator *(Entropy left, double right) + { + return new Entropy(left.Value * right, left.Unit); + } + + public static Entropy operator /(Entropy left, double right) + { + return new Entropy(left.Value / right, left.Unit); + } + + public static double operator /(Entropy left, Entropy right) + { + return left.JoulesPerKelvin / right.JoulesPerKelvin; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Entropy left, Entropy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Entropy left, Entropy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Entropy left, Entropy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Entropy left, Entropy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs new file mode 100644 index 0000000000..9bf4cbd0a1 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs @@ -0,0 +1,792 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Force : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Force, which is Newton. All conversions go via this value. + /// + public static ForceUnit BaseUnit => ForceUnit.Newton; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Force; + + /// + /// All units of measurement for the Force quantity. + /// + public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Newton. + /// + public static Force Zero => new Force(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 ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Force.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Force.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Micronewtons. + /// + public double Micronewtons => As(ForceUnit.Micronewton); + + /// + /// Get Force in Millinewtons. + /// + public double Millinewtons => As(ForceUnit.Millinewton); + + /// + /// Get Force in Newtons. + /// + public double Newtons => As(ForceUnit.Newton); + + /// + /// Get Force in OunceForce. + /// + public double OunceForce => As(ForceUnit.OunceForce); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceUnit 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(ForceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Force from Decanewtons. + /// + /// If value is NaN or Infinity. + public static Force FromDecanewtons(QuantityValue decanewtons) + { + double value = (double) decanewtons; + return new Force(value, ForceUnit.Decanewton); + } + /// + /// Get Force from Dyne. + /// + /// If value is NaN or Infinity. + public static Force FromDyne(QuantityValue dyne) + { + double value = (double) dyne; + return new Force(value, ForceUnit.Dyn); + } + /// + /// Get Force from KilogramsForce. + /// + /// If value is NaN or Infinity. + public static Force FromKilogramsForce(QuantityValue kilogramsforce) + { + double value = (double) kilogramsforce; + return new Force(value, ForceUnit.KilogramForce); + } + /// + /// Get Force from Kilonewtons. + /// + /// If value is NaN or Infinity. + public static Force FromKilonewtons(QuantityValue kilonewtons) + { + double value = (double) kilonewtons; + return new Force(value, ForceUnit.Kilonewton); + } + /// + /// Get Force from KiloPonds. + /// + /// If value is NaN or Infinity. + public static Force FromKiloPonds(QuantityValue kiloponds) + { + double value = (double) kiloponds; + return new Force(value, ForceUnit.KiloPond); + } + /// + /// Get Force from Meganewtons. + /// + /// If value is NaN or Infinity. + public static Force FromMeganewtons(QuantityValue meganewtons) + { + double value = (double) meganewtons; + return new Force(value, ForceUnit.Meganewton); + } + /// + /// Get Force from Micronewtons. + /// + /// If value is NaN or Infinity. + public static Force FromMicronewtons(QuantityValue micronewtons) + { + double value = (double) micronewtons; + return new Force(value, ForceUnit.Micronewton); + } + /// + /// Get Force from Millinewtons. + /// + /// If value is NaN or Infinity. + public static Force FromMillinewtons(QuantityValue millinewtons) + { + double value = (double) millinewtons; + return new Force(value, ForceUnit.Millinewton); + } + /// + /// Get Force from Newtons. + /// + /// If value is NaN or Infinity. + public static Force FromNewtons(QuantityValue newtons) + { + double value = (double) newtons; + return new Force(value, ForceUnit.Newton); + } + /// + /// Get Force from OunceForce. + /// + /// If value is NaN or Infinity. + public static Force FromOunceForce(QuantityValue ounceforce) + { + double value = (double) ounceforce; + return new Force(value, ForceUnit.OunceForce); + } + /// + /// Get Force from Poundals. + /// + /// If value is NaN or Infinity. + public static Force FromPoundals(QuantityValue poundals) + { + double value = (double) poundals; + return new Force(value, ForceUnit.Poundal); + } + /// + /// Get Force from PoundsForce. + /// + /// If value is NaN or Infinity. + public static Force FromPoundsForce(QuantityValue poundsforce) + { + double value = (double) poundsforce; + return new Force(value, ForceUnit.PoundForce); + } + /// + /// Get Force from TonnesForce. + /// + /// If value is NaN or Infinity. + public static Force FromTonnesForce(QuantityValue tonnesforce) + { + 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. + public static Force From(QuantityValue value, ForceUnit fromUnit) + { + return new Force((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Force Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Force result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Force result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ForceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ForceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Force operator -(Force right) + { + return new Force(-right.Value, right.Unit); + } + + public static Force operator +(Force left, Force right) + { + return new Force(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Force operator -(Force left, Force right) + { + return new Force(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Force operator *(double left, Force right) + { + return new Force(left * right.Value, right.Unit); + } + + public static Force operator *(Force left, double right) + { + return new Force(left.Value * right, left.Unit); + } + + public static Force operator /(Force left, double right) + { + return new Force(left.Value / right, left.Unit); + } + + public static double operator /(Force left, Force right) + { + return left.Newtons / right.Newtons; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Force left, Force right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Force left, Force right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Force left, Force right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Force left, Force 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.Micronewton: return (_value) * 1e-6d; + case ForceUnit.Millinewton: return (_value) * 1e-3d; + case ForceUnit.Newton: return _value; + case ForceUnit.OunceForce: return _value*2.780138509537812e-1; + 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.Micronewton: return (baseUnitValue) / 1e-6d; + case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; + case ForceUnit.Newton: return baseUnitValue; + case ForceUnit.OunceForce: return baseUnitValue/2.780138509537812e-1; + 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs new file mode 100644 index 0000000000..20dc3630b2 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs @@ -0,0 +1,760 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct ForceChangeRate : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceChangeRateUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. + /// + public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ForceChangeRate; + + /// + /// All units of measurement for the ForceChangeRate quantity. + /// + public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. + /// + public static ForceChangeRate Zero => new ForceChangeRate(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 ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForceChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceChangeRateUnit 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(ForceChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ForceChangeRate from CentinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) + { + double value = (double) centinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); + } + /// + /// Get ForceChangeRate from DecanewtonsPerMinute. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) + { + double value = (double) decanewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); + } + /// + /// Get ForceChangeRate from DecanewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) + { + double value = (double) decanewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); + } + /// + /// Get ForceChangeRate from DecinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) + { + double value = (double) decinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); + } + /// + /// Get ForceChangeRate from KilonewtonsPerMinute. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) + { + double value = (double) kilonewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); + } + /// + /// Get ForceChangeRate from KilonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) + { + double value = (double) kilonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); + } + /// + /// Get ForceChangeRate from MicronewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) + { + double value = (double) micronewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); + } + /// + /// Get ForceChangeRate from MillinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) + { + double value = (double) millinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); + } + /// + /// Get ForceChangeRate from NanonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) + { + double value = (double) nanonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); + } + /// + /// Get ForceChangeRate from NewtonsPerMinute. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) + { + double value = (double) newtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); + } + /// + /// Get ForceChangeRate from NewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) + { + 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. + public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) + { + return new ForceChangeRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ForceChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ForceChangeRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ForceChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ForceChangeRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ForceChangeRate operator -(ForceChangeRate right) + { + return new ForceChangeRate(-right.Value, right.Unit); + } + + public static ForceChangeRate operator +(ForceChangeRate left, ForceChangeRate right) + { + return new ForceChangeRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ForceChangeRate operator -(ForceChangeRate left, ForceChangeRate right) + { + return new ForceChangeRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ForceChangeRate operator *(double left, ForceChangeRate right) + { + return new ForceChangeRate(left * right.Value, right.Unit); + } + + public static ForceChangeRate operator *(ForceChangeRate left, double right) + { + return new ForceChangeRate(left.Value * right, left.Unit); + } + + public static ForceChangeRate operator /(ForceChangeRate left, double right) + { + return new ForceChangeRate(left.Value / right, left.Unit); + } + + public static double operator /(ForceChangeRate left, ForceChangeRate right) + { + return left.NewtonsPerSecond / right.NewtonsPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ForceChangeRate left, ForceChangeRate right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ForceChangeRate left, ForceChangeRate right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ForceChangeRate left, ForceChangeRate right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ForceChangeRate left, ForceChangeRate 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs new file mode 100644 index 0000000000..201b21a8c9 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs @@ -0,0 +1,728 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The magnitude of force per unit length. + /// + public partial struct ForcePerLength : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForcePerLengthUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. + /// + public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ForcePerLength; + + /// + /// All units of measurement for the ForcePerLength quantity. + /// + public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. + /// + public static ForcePerLength Zero => new ForcePerLength(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 ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForcePerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForcePerLengthUnit 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(ForcePerLengthUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ForcePerLength from CentinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) + { + double value = (double) centinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); + } + /// + /// Get ForcePerLength from DecinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) + { + double value = (double) decinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); + } + /// + /// Get ForcePerLength from KilogramsForcePerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) + { + double value = (double) kilogramsforcepermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); + } + /// + /// Get ForcePerLength from KilonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) + { + double value = (double) kilonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); + } + /// + /// Get ForcePerLength from MeganewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) + { + double value = (double) meganewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); + } + /// + /// Get ForcePerLength from MicronewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) + { + double value = (double) micronewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); + } + /// + /// Get ForcePerLength from MillinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) + { + double value = (double) millinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); + } + /// + /// Get ForcePerLength from NanonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) + { + double value = (double) nanonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); + } + /// + /// Get ForcePerLength from NewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) + { + 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. + public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) + { + return new ForcePerLength((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ForcePerLength Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ForcePerLength result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ForcePerLength result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ForcePerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ForcePerLengthUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ForcePerLength operator -(ForcePerLength right) + { + return new ForcePerLength(-right.Value, right.Unit); + } + + public static ForcePerLength operator +(ForcePerLength left, ForcePerLength right) + { + return new ForcePerLength(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ForcePerLength operator -(ForcePerLength left, ForcePerLength right) + { + return new ForcePerLength(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ForcePerLength operator *(double left, ForcePerLength right) + { + return new ForcePerLength(left * right.Value, right.Unit); + } + + public static ForcePerLength operator *(ForcePerLength left, double right) + { + return new ForcePerLength(left.Value * right, left.Unit); + } + + public static ForcePerLength operator /(ForcePerLength left, double right) + { + return new ForcePerLength(left.Value / right, left.Unit); + } + + public static double operator /(ForcePerLength left, ForcePerLength right) + { + return left.NewtonsPerMeter / right.NewtonsPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ForcePerLength left, ForcePerLength right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ForcePerLength left, ForcePerLength right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ForcePerLength left, ForcePerLength right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ForcePerLength left, ForcePerLength 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs new file mode 100644 index 0000000000..49959d51ca --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs @@ -0,0 +1,712 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The number of occurrences of a repeating event per unit time. + /// + public partial struct Frequency : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FrequencyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Frequency, which is Hertz. All conversions go via this value. + /// + public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Frequency; + + /// + /// All units of measurement for the Frequency quantity. + /// + public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. + /// + public static Frequency Zero => new Frequency(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 FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Frequency.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Frequency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(FrequencyUnit 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(FrequencyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Frequency from CyclesPerHour. + /// + /// If value is NaN or Infinity. + public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) + { + double value = (double) cyclesperhour; + return new Frequency(value, FrequencyUnit.CyclePerHour); + } + /// + /// Get Frequency from CyclesPerMinute. + /// + /// If value is NaN or Infinity. + public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) + { + double value = (double) cyclesperminute; + return new Frequency(value, FrequencyUnit.CyclePerMinute); + } + /// + /// Get Frequency from Gigahertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromGigahertz(QuantityValue gigahertz) + { + double value = (double) gigahertz; + return new Frequency(value, FrequencyUnit.Gigahertz); + } + /// + /// Get Frequency from Hertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromHertz(QuantityValue hertz) + { + double value = (double) hertz; + return new Frequency(value, FrequencyUnit.Hertz); + } + /// + /// Get Frequency from Kilohertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromKilohertz(QuantityValue kilohertz) + { + double value = (double) kilohertz; + return new Frequency(value, FrequencyUnit.Kilohertz); + } + /// + /// Get Frequency from Megahertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromMegahertz(QuantityValue megahertz) + { + double value = (double) megahertz; + return new Frequency(value, FrequencyUnit.Megahertz); + } + /// + /// Get Frequency from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) + { + double value = (double) radianspersecond; + return new Frequency(value, FrequencyUnit.RadianPerSecond); + } + /// + /// Get Frequency from Terahertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromTerahertz(QuantityValue terahertz) + { + 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. + public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) + { + return new Frequency((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Frequency Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Frequency result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Frequency result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 FrequencyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out FrequencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 FrequencyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Frequency operator -(Frequency right) + { + return new Frequency(-right.Value, right.Unit); + } + + public static Frequency operator +(Frequency left, Frequency right) + { + return new Frequency(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Frequency operator -(Frequency left, Frequency right) + { + return new Frequency(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Frequency operator *(double left, Frequency right) + { + return new Frequency(left * right.Value, right.Unit); + } + + public static Frequency operator *(Frequency left, double right) + { + return new Frequency(left.Value * right, left.Unit); + } + + public static Frequency operator /(Frequency left, double right) + { + return new Frequency(left.Value / right, left.Unit); + } + + public static double operator /(Frequency left, Frequency right) + { + return left.Hertz / right.Hertz; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Frequency left, Frequency right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Frequency left, Frequency right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Frequency left, Frequency right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Frequency left, Frequency 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs new file mode 100644 index 0000000000..8005e0e610 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs @@ -0,0 +1,840 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Heat flux is the flow of energy per unit of area per unit of time + /// + public partial struct HeatFlux : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatFluxUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. + /// + public static HeatFluxUnit BaseUnit => HeatFluxUnit.WattPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.HeatFlux; + + /// + /// All units of measurement for the HeatFlux quantity. + /// + public static HeatFluxUnit[] Units { get; } = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static HeatFlux Zero => new HeatFlux(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 HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatFluxUnit 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(HeatFluxUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get HeatFlux from BtusPerHourSquareFoot. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquarefoot) + { + double value = (double) btusperhoursquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); + } + /// + /// Get HeatFlux from BtusPerMinuteSquareFoot. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesquarefoot) + { + double value = (double) btusperminutesquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); + } + /// + /// Get HeatFlux from BtusPerSecondSquareFoot. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsquarefoot) + { + double value = (double) btuspersecondsquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); + } + /// + /// Get HeatFlux from BtusPerSecondSquareInch. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsquareinch) + { + double value = (double) btuspersecondsquareinch; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); + } + /// + /// Get HeatFlux from CaloriesPerSecondSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue caloriespersecondsquarecentimeter) + { + double value = (double) caloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); + } + /// + /// Get HeatFlux from CentiwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspersquaremeter) + { + double value = (double) centiwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); + } + /// + /// Get HeatFlux from DeciwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersquaremeter) + { + double value = (double) deciwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); + } + /// + /// Get HeatFlux from KilocaloriesPerHourSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocaloriesperhoursquaremeter) + { + double value = (double) kilocaloriesperhoursquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); + } + /// + /// Get HeatFlux from KilocaloriesPerSecondSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue kilocaloriespersecondsquarecentimeter) + { + double value = (double) kilocaloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + } + /// + /// Get HeatFlux from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); + } + /// + /// Get HeatFlux from MicrowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) + { + double value = (double) microwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); + } + /// + /// Get HeatFlux from MilliwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) + { + double value = (double) milliwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); + } + /// + /// Get HeatFlux from NanowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) + { + double value = (double) nanowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); + } + /// + /// Get HeatFlux from WattsPerSquareFoot. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) + { + double value = (double) wattspersquarefoot; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); + } + /// + /// Get HeatFlux from WattsPerSquareInch. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) + { + double value = (double) wattspersquareinch; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); + } + /// + /// Get HeatFlux from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) + { + 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. + public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) + { + return new HeatFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 HeatFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out HeatFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 HeatFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 HeatFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out HeatFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 HeatFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static HeatFlux operator -(HeatFlux right) + { + return new HeatFlux(-right.Value, right.Unit); + } + + public static HeatFlux operator +(HeatFlux left, HeatFlux right) + { + return new HeatFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static HeatFlux operator -(HeatFlux left, HeatFlux right) + { + return new HeatFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static HeatFlux operator *(double left, HeatFlux right) + { + return new HeatFlux(left * right.Value, right.Unit); + } + + public static HeatFlux operator *(HeatFlux left, double right) + { + return new HeatFlux(left.Value * right, left.Unit); + } + + public static HeatFlux operator /(HeatFlux left, double right) + { + return new HeatFlux(left.Value / right, left.Unit); + } + + public static double operator /(HeatFlux left, HeatFlux right) + { + return left.WattsPerSquareMeter / right.WattsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(HeatFlux left, HeatFlux right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(HeatFlux left, HeatFlux right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(HeatFlux left, HeatFlux right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(HeatFlux left, HeatFlux 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs new file mode 100644 index 0000000000..6c6624f9ed --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs @@ -0,0 +1,616 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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) + /// + public partial struct HeatTransferCoefficient : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatTransferCoefficientUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. + /// + public static HeatTransferCoefficientUnit BaseUnit => HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.HeatTransferCoefficient; + + /// + /// All units of measurement for the HeatTransferCoefficient quantity. + /// + public static HeatTransferCoefficientUnit[] Units { get; } = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. + /// + public static HeatTransferCoefficient Zero => new HeatTransferCoefficient(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 HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatTransferCoefficient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterCelsius. + /// + public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterKelvin. + /// + public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatTransferCoefficientUnit 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(HeatTransferCoefficientUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterCelsius. + /// + /// If value is NaN or Infinity. + public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue wattspersquaremetercelsius) + { + double value = (double) wattspersquaremetercelsius; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + } + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterKelvin. + /// + /// If value is NaN or Infinity. + public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue wattspersquaremeterkelvin) + { + 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. + public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) + { + return new HeatTransferCoefficient((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 HeatTransferCoefficient Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out HeatTransferCoefficient result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 HeatTransferCoefficient result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 HeatTransferCoefficientUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static HeatTransferCoefficient operator -(HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(-right.Value, right.Unit); + } + + public static HeatTransferCoefficient operator +(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static HeatTransferCoefficient operator -(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static HeatTransferCoefficient operator *(double left, HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(left * right.Value, right.Unit); + } + + public static HeatTransferCoefficient operator *(HeatTransferCoefficient left, double right) + { + return new HeatTransferCoefficient(left.Value * right, left.Unit); + } + + public static HeatTransferCoefficient operator /(HeatTransferCoefficient left, double right) + { + return new HeatTransferCoefficient(left.Value / right, left.Unit); + } + + public static double operator /(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.WattsPerSquareMeterKelvin / right.WattsPerSquareMeterKelvin; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(HeatTransferCoefficient left, HeatTransferCoefficient 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs new file mode 100644 index 0000000000..e565b6477a --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs @@ -0,0 +1,651 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. + /// + /// + /// https://en.wikipedia.org/wiki/Illuminance + /// + public partial struct Illuminance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IlluminanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Illuminance, which is Lux. All conversions go via this value. + /// + public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Illuminance; + + /// + /// All units of measurement for the Illuminance quantity. + /// + public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lux. + /// + public static Illuminance Zero => new Illuminance(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 IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Illuminance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Illuminance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IlluminanceUnit 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(IlluminanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Illuminance from Kilolux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromKilolux(QuantityValue kilolux) + { + double value = (double) kilolux; + return new Illuminance(value, IlluminanceUnit.Kilolux); + } + /// + /// Get Illuminance from Lux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromLux(QuantityValue lux) + { + double value = (double) lux; + return new Illuminance(value, IlluminanceUnit.Lux); + } + /// + /// Get Illuminance from Megalux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromMegalux(QuantityValue megalux) + { + double value = (double) megalux; + return new Illuminance(value, IlluminanceUnit.Megalux); + } + /// + /// Get Illuminance from Millilux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromMillilux(QuantityValue millilux) + { + 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. + public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) + { + return new Illuminance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Illuminance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Illuminance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Illuminance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 IlluminanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IlluminanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 IlluminanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Illuminance operator -(Illuminance right) + { + return new Illuminance(-right.Value, right.Unit); + } + + public static Illuminance operator +(Illuminance left, Illuminance right) + { + return new Illuminance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Illuminance operator -(Illuminance left, Illuminance right) + { + return new Illuminance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Illuminance operator *(double left, Illuminance right) + { + return new Illuminance(left * right.Value, right.Unit); + } + + public static Illuminance operator *(Illuminance left, double right) + { + return new Illuminance(left.Value * right, left.Unit); + } + + public static Illuminance operator /(Illuminance left, double right) + { + return new Illuminance(left.Value / right, left.Unit); + } + + public static double operator /(Illuminance left, Illuminance right) + { + return left.Lux / right.Lux; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Illuminance left, Illuminance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Illuminance left, Illuminance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Illuminance left, Illuminance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Illuminance left, Illuminance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs new file mode 100644 index 0000000000..285b42268a --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs @@ -0,0 +1,616 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. + /// + public partial struct Irradiance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradianceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. + /// + public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Irradiance; + + /// + /// All units of measurement for the Irradiance quantity. + /// + public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static Irradiance Zero => new Irradiance(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 IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Irradiance in KilowattsPerSquareMeter. + /// + public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + + /// + /// Get Irradiance in WattsPerSquareMeter. + /// + public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradianceUnit 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(IrradianceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiance from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); + } + /// + /// Get Irradiance from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) + { + 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. + public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) + { + return new Irradiance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Irradiance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Irradiance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Irradiance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 IrradianceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IrradianceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 IrradianceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Irradiance operator -(Irradiance right) + { + return new Irradiance(-right.Value, right.Unit); + } + + public static Irradiance operator +(Irradiance left, Irradiance right) + { + return new Irradiance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Irradiance operator -(Irradiance left, Irradiance right) + { + return new Irradiance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Irradiance operator *(double left, Irradiance right) + { + return new Irradiance(left * right.Value, right.Unit); + } + + public static Irradiance operator *(Irradiance left, double right) + { + return new Irradiance(left.Value * right, left.Unit); + } + + public static Irradiance operator /(Irradiance left, double right) + { + return new Irradiance(left.Value / right, left.Unit); + } + + public static double operator /(Irradiance left, Irradiance right) + { + return left.WattsPerSquareMeter / right.WattsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Irradiance left, Irradiance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Irradiance left, Irradiance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Irradiance left, Irradiance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Irradiance left, Irradiance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs new file mode 100644 index 0000000000..60a18e3ee3 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs @@ -0,0 +1,635 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Irradiation + /// + public partial struct Irradiation : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradiationUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. + /// + public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Irradiation; + + /// + /// All units of measurement for the Irradiation quantity. + /// + public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. + /// + public static Irradiation Zero => new Irradiation(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 IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiation.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiation.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradiationUnit 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(IrradiationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiation from JoulesPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) + { + double value = (double) joulespersquaremeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); + } + /// + /// Get Irradiation from KilowattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) + { + double value = (double) kilowatthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); + } + /// + /// Get Irradiation from WattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) + { + 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. + public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) + { + return new Irradiation((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Irradiation Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Irradiation result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Irradiation result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 IrradiationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IrradiationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 IrradiationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Irradiation operator -(Irradiation right) + { + return new Irradiation(-right.Value, right.Unit); + } + + public static Irradiation operator +(Irradiation left, Irradiation right) + { + return new Irradiation(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Irradiation operator -(Irradiation left, Irradiation right) + { + return new Irradiation(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Irradiation operator *(double left, Irradiation right) + { + return new Irradiation(left * right.Value, right.Unit); + } + + public static Irradiation operator *(Irradiation left, double right) + { + return new Irradiation(left.Value * right, left.Unit); + } + + public static Irradiation operator /(Irradiation left, double right) + { + return new Irradiation(left.Value / right, left.Unit); + } + + public static double operator /(Irradiation left, Irradiation right) + { + return left.JoulesPerSquareMeter / right.JoulesPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Irradiation left, Irradiation right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Irradiation left, Irradiation right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Irradiation left, Irradiation right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Irradiation left, Irradiation 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs new file mode 100644 index 0000000000..27c4a59d9a --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs @@ -0,0 +1,715 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// http://en.wikipedia.org/wiki/Viscosity + /// + public partial struct KinematicViscosity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly KinematicViscosityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. + /// + public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.KinematicViscosity; + + /// + /// All units of measurement for the KinematicViscosity quantity. + /// + public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. + /// + public static KinematicViscosity Zero => new KinematicViscosity(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 KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => KinematicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(KinematicViscosityUnit 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(KinematicViscosityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get KinematicViscosity from Centistokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromCentistokes(QuantityValue centistokes) + { + double value = (double) centistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); + } + /// + /// Get KinematicViscosity from Decistokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromDecistokes(QuantityValue decistokes) + { + double value = (double) decistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); + } + /// + /// Get KinematicViscosity from Kilostokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) + { + double value = (double) kilostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); + } + /// + /// Get KinematicViscosity from Microstokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) + { + double value = (double) microstokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); + } + /// + /// Get KinematicViscosity from Millistokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromMillistokes(QuantityValue millistokes) + { + double value = (double) millistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); + } + /// + /// Get KinematicViscosity from Nanostokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) + { + double value = (double) nanostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); + } + /// + /// Get KinematicViscosity from SquareMetersPerSecond. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) + { + double value = (double) squaremeterspersecond; + return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); + } + /// + /// Get KinematicViscosity from Stokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromStokes(QuantityValue stokes) + { + 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. + public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) + { + return new KinematicViscosity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 KinematicViscosity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out KinematicViscosity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 KinematicViscosity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 KinematicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 KinematicViscosityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static KinematicViscosity operator -(KinematicViscosity right) + { + return new KinematicViscosity(-right.Value, right.Unit); + } + + public static KinematicViscosity operator +(KinematicViscosity left, KinematicViscosity right) + { + return new KinematicViscosity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static KinematicViscosity operator -(KinematicViscosity left, KinematicViscosity right) + { + return new KinematicViscosity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static KinematicViscosity operator *(double left, KinematicViscosity right) + { + return new KinematicViscosity(left * right.Value, right.Unit); + } + + public static KinematicViscosity operator *(KinematicViscosity left, double right) + { + return new KinematicViscosity(left.Value * right, left.Unit); + } + + public static KinematicViscosity operator /(KinematicViscosity left, double right) + { + return new KinematicViscosity(left.Value / right, left.Unit); + } + + public static double operator /(KinematicViscosity left, KinematicViscosity right) + { + return left.SquareMetersPerSecond / right.SquareMetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(KinematicViscosity left, KinematicViscosity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(KinematicViscosity left, KinematicViscosity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(KinematicViscosity left, KinematicViscosity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(KinematicViscosity left, KinematicViscosity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs new file mode 100644 index 0000000000..26d834afad --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs @@ -0,0 +1,600 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct LapseRate : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LapseRateUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value. + /// + public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LapseRate; + + /// + /// All units of measurement for the LapseRate quantity. + /// + public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. + /// + public static LapseRate Zero => new LapseRate(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 LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LapseRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LapseRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LapseRate in DegreesCelciusPerKilometer. + /// + public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LapseRateUnit 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(LapseRateUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LapseRate from DegreesCelciusPerKilometer. + /// + /// If value is NaN or Infinity. + public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) + { + 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. + public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) + { + return new LapseRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LapseRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LapseRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LapseRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LapseRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LapseRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LapseRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static LapseRate operator -(LapseRate right) + { + return new LapseRate(-right.Value, right.Unit); + } + + public static LapseRate operator +(LapseRate left, LapseRate right) + { + return new LapseRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LapseRate operator -(LapseRate left, LapseRate right) + { + return new LapseRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LapseRate operator *(double left, LapseRate right) + { + return new LapseRate(left * right.Value, right.Unit); + } + + public static LapseRate operator *(LapseRate left, double right) + { + return new LapseRate(left.Value * right, left.Unit); + } + + public static LapseRate operator /(LapseRate left, double right) + { + return new LapseRate(left.Value / right, left.Unit); + } + + public static double operator /(LapseRate left, LapseRate right) + { + return left.DegreesCelciusPerKilometer / right.DegreesCelciusPerKilometer; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(LapseRate left, LapseRate right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(LapseRate left, LapseRate right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(LapseRate left, LapseRate right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(LapseRate left, LapseRate 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs new file mode 100644 index 0000000000..96e9b0c092 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs @@ -0,0 +1,635 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// http://en.wikipedia.org/wiki/Linear_density + /// + public partial struct LinearDensity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LinearDensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. + /// + public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LinearDensity; + + /// + /// All units of measurement for the LinearDensity quantity. + /// + public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. + /// + public static LinearDensity Zero => new LinearDensity(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 LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LinearDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LinearDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LinearDensityUnit 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(LinearDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LinearDensity from GramsPerMeter. + /// + /// If value is NaN or Infinity. + public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) + { + double value = (double) gramspermeter; + return new LinearDensity(value, LinearDensityUnit.GramPerMeter); + } + /// + /// Get LinearDensity from KilogramsPerMeter. + /// + /// If value is NaN or Infinity. + public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) + { + double value = (double) kilogramspermeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); + } + /// + /// Get LinearDensity from PoundsPerFoot. + /// + /// If value is NaN or Infinity. + public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) + { + 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. + public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) + { + return new LinearDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LinearDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LinearDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LinearDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LinearDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LinearDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LinearDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static LinearDensity operator -(LinearDensity right) + { + return new LinearDensity(-right.Value, right.Unit); + } + + public static LinearDensity operator +(LinearDensity left, LinearDensity right) + { + return new LinearDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LinearDensity operator -(LinearDensity left, LinearDensity right) + { + return new LinearDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LinearDensity operator *(double left, LinearDensity right) + { + return new LinearDensity(left * right.Value, right.Unit); + } + + public static LinearDensity operator *(LinearDensity left, double right) + { + return new LinearDensity(left.Value * right, left.Unit); + } + + public static LinearDensity operator /(LinearDensity left, double right) + { + return new LinearDensity(left.Value / right, left.Unit); + } + + public static double operator /(LinearDensity left, LinearDensity right) + { + return left.KilogramsPerMeter / right.KilogramsPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(LinearDensity left, LinearDensity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(LinearDensity left, LinearDensity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(LinearDensity left, LinearDensity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(LinearDensity left, LinearDensity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs new file mode 100644 index 0000000000..d7aaa86a5f --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. + /// + /// + /// https://en.wikipedia.org/wiki/Luminous_flux + /// + public partial struct LuminousFlux : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousFluxUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. + /// + public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LuminousFlux; + + /// + /// All units of measurement for the LuminousFlux quantity. + /// + public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. + /// + public static LuminousFlux Zero => new LuminousFlux(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 LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousFlux in Lumens. + /// + public double Lumens => As(LuminousFluxUnit.Lumen); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousFluxUnit 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(LuminousFluxUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LuminousFlux from Lumens. + /// + /// If value is NaN or Infinity. + public static LuminousFlux FromLumens(QuantityValue lumens) + { + 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. + public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) + { + return new LuminousFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LuminousFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LuminousFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LuminousFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LuminousFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LuminousFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LuminousFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static LuminousFlux operator -(LuminousFlux right) + { + return new LuminousFlux(-right.Value, right.Unit); + } + + public static LuminousFlux operator +(LuminousFlux left, LuminousFlux right) + { + return new LuminousFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LuminousFlux operator -(LuminousFlux left, LuminousFlux right) + { + return new LuminousFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LuminousFlux operator *(double left, LuminousFlux right) + { + return new LuminousFlux(left * right.Value, right.Unit); + } + + public static LuminousFlux operator *(LuminousFlux left, double right) + { + return new LuminousFlux(left.Value * right, left.Unit); + } + + public static LuminousFlux operator /(LuminousFlux left, double right) + { + return new LuminousFlux(left.Value / right, left.Unit); + } + + public static double operator /(LuminousFlux left, LuminousFlux right) + { + return left.Lumens / right.Lumens; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(LuminousFlux left, LuminousFlux right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(LuminousFlux left, LuminousFlux right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(LuminousFlux left, LuminousFlux right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(LuminousFlux left, LuminousFlux 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs new file mode 100644 index 0000000000..2f70b17d03 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Luminous_intensity + /// + public partial struct LuminousIntensity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousIntensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. + /// + public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; + + /// + /// 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 static QuantityType QuantityType => QuantityType.LuminousIntensity; + + /// + /// All units of measurement for the LuminousIntensity quantity. + /// + public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Candela. + /// + public static LuminousIntensity Zero => new LuminousIntensity(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 LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousIntensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousIntensity in Candela. + /// + public double Candela => As(LuminousIntensityUnit.Candela); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousIntensityUnit 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(LuminousIntensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LuminousIntensity from Candela. + /// + /// If value is NaN or Infinity. + public static LuminousIntensity FromCandela(QuantityValue candela) + { + 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. + public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) + { + return new LuminousIntensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 LuminousIntensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LuminousIntensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 LuminousIntensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 LuminousIntensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 LuminousIntensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static LuminousIntensity operator -(LuminousIntensity right) + { + return new LuminousIntensity(-right.Value, right.Unit); + } + + public static LuminousIntensity operator +(LuminousIntensity left, LuminousIntensity right) + { + return new LuminousIntensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LuminousIntensity operator -(LuminousIntensity left, LuminousIntensity right) + { + return new LuminousIntensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static LuminousIntensity operator *(double left, LuminousIntensity right) + { + return new LuminousIntensity(left * right.Value, right.Unit); + } + + public static LuminousIntensity operator *(LuminousIntensity left, double right) + { + return new LuminousIntensity(left.Value * right, left.Unit); + } + + public static LuminousIntensity operator /(LuminousIntensity left, double right) + { + return new LuminousIntensity(left.Value / right, left.Unit); + } + + public static double operator /(LuminousIntensity left, LuminousIntensity right) + { + return left.Candela / right.Candela; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(LuminousIntensity left, LuminousIntensity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(LuminousIntensity left, LuminousIntensity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(LuminousIntensity left, LuminousIntensity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(LuminousIntensity left, LuminousIntensity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs new file mode 100644 index 0000000000..2e4ced2daf --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Magnetic_field + /// + public partial struct MagneticField : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFieldUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticField, which is Tesla. All conversions go via this value. + /// + public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MagneticField; + + /// + /// All units of measurement for the MagneticField quantity. + /// + public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. + /// + public static MagneticField Zero => new MagneticField(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 MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticField in Teslas. + /// + public double Teslas => As(MagneticFieldUnit.Tesla); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFieldUnit 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(MagneticFieldUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MagneticField from Teslas. + /// + /// If value is NaN or Infinity. + public static MagneticField FromTeslas(QuantityValue teslas) + { + 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. + public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) + { + return new MagneticField((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MagneticField Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MagneticField result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MagneticField result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MagneticFieldUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagneticFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MagneticFieldUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MagneticField operator -(MagneticField right) + { + return new MagneticField(-right.Value, right.Unit); + } + + public static MagneticField operator +(MagneticField left, MagneticField right) + { + return new MagneticField(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MagneticField operator -(MagneticField left, MagneticField right) + { + return new MagneticField(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MagneticField operator *(double left, MagneticField right) + { + return new MagneticField(left * right.Value, right.Unit); + } + + public static MagneticField operator *(MagneticField left, double right) + { + return new MagneticField(left.Value * right, left.Unit); + } + + public static MagneticField operator /(MagneticField left, double right) + { + return new MagneticField(left.Value / right, left.Unit); + } + + public static double operator /(MagneticField left, MagneticField right) + { + return left.Teslas / right.Teslas; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MagneticField left, MagneticField right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MagneticField left, MagneticField right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MagneticField left, MagneticField right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MagneticField left, MagneticField 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs new file mode 100644 index 0000000000..9a5151b38c --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Magnetic_flux + /// + public partial struct MagneticFlux : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFluxUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. + /// + public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MagneticFlux; + + /// + /// All units of measurement for the MagneticFlux quantity. + /// + public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Weber. + /// + public static MagneticFlux Zero => new MagneticFlux(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 MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticFlux in Webers. + /// + public double Webers => As(MagneticFluxUnit.Weber); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFluxUnit 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(MagneticFluxUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MagneticFlux from Webers. + /// + /// If value is NaN or Infinity. + public static MagneticFlux FromWebers(QuantityValue webers) + { + 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. + public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) + { + return new MagneticFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MagneticFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MagneticFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MagneticFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MagneticFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagneticFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MagneticFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MagneticFlux operator -(MagneticFlux right) + { + return new MagneticFlux(-right.Value, right.Unit); + } + + public static MagneticFlux operator +(MagneticFlux left, MagneticFlux right) + { + return new MagneticFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MagneticFlux operator -(MagneticFlux left, MagneticFlux right) + { + return new MagneticFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MagneticFlux operator *(double left, MagneticFlux right) + { + return new MagneticFlux(left * right.Value, right.Unit); + } + + public static MagneticFlux operator *(MagneticFlux left, double right) + { + return new MagneticFlux(left.Value * right, left.Unit); + } + + public static MagneticFlux operator /(MagneticFlux left, double right) + { + return new MagneticFlux(left.Value / right, left.Unit); + } + + public static double operator /(MagneticFlux left, MagneticFlux right) + { + return left.Webers / right.Webers; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MagneticFlux left, MagneticFlux right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MagneticFlux left, MagneticFlux right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MagneticFlux left, MagneticFlux right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MagneticFlux left, MagneticFlux 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs new file mode 100644 index 0000000000..9c4be74aac --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Magnetization + /// + public partial struct Magnetization : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagnetizationUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. + /// + public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Magnetization; + + /// + /// All units of measurement for the Magnetization quantity. + /// + public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. + /// + public static Magnetization Zero => new Magnetization(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 MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Magnetization.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Magnetization.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Magnetization in AmperesPerMeter. + /// + public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagnetizationUnit 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(MagnetizationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Magnetization from AmperesPerMeter. + /// + /// If value is NaN or Infinity. + public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) + { + 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. + public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) + { + return new Magnetization((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Magnetization Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Magnetization result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Magnetization result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MagnetizationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagnetizationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MagnetizationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Magnetization operator -(Magnetization right) + { + return new Magnetization(-right.Value, right.Unit); + } + + public static Magnetization operator +(Magnetization left, Magnetization right) + { + return new Magnetization(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Magnetization operator -(Magnetization left, Magnetization right) + { + return new Magnetization(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Magnetization operator *(double left, Magnetization right) + { + return new Magnetization(left * right.Value, right.Unit); + } + + public static Magnetization operator *(Magnetization left, double right) + { + return new Magnetization(left.Value * right, left.Unit); + } + + public static Magnetization operator /(Magnetization left, double right) + { + return new Magnetization(left.Value / right, left.Unit); + } + + public static double operator /(Magnetization left, Magnetization right) + { + return left.AmperesPerMeter / right.AmperesPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Magnetization left, Magnetization right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Magnetization left, Magnetization right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Magnetization left, Magnetization right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Magnetization left, Magnetization 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs new file mode 100644 index 0000000000..0f35914d2b --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs @@ -0,0 +1,936 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct Mass : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Mass, which is Kilogram. All conversions go via this value. + /// + public static MassUnit BaseUnit => MassUnit.Kilogram; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Mass; + + /// + /// All units of measurement for the Mass quantity. + /// + public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. + /// + public static Mass Zero => new Mass(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 MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Mass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Mass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassUnit 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(MassUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Mass from Centigrams. + /// + /// If value is NaN or Infinity. + public static Mass FromCentigrams(QuantityValue centigrams) + { + double value = (double) centigrams; + return new Mass(value, MassUnit.Centigram); + } + /// + /// Get Mass from Decagrams. + /// + /// If value is NaN or Infinity. + public static Mass FromDecagrams(QuantityValue decagrams) + { + double value = (double) decagrams; + return new Mass(value, MassUnit.Decagram); + } + /// + /// Get Mass from Decigrams. + /// + /// If value is NaN or Infinity. + public static Mass FromDecigrams(QuantityValue decigrams) + { + double value = (double) decigrams; + return new Mass(value, MassUnit.Decigram); + } + /// + /// Get Mass from Grams. + /// + /// If value is NaN or Infinity. + public static Mass FromGrams(QuantityValue grams) + { + double value = (double) grams; + return new Mass(value, MassUnit.Gram); + } + /// + /// Get Mass from Hectograms. + /// + /// If value is NaN or Infinity. + public static Mass FromHectograms(QuantityValue hectograms) + { + double value = (double) hectograms; + return new Mass(value, MassUnit.Hectogram); + } + /// + /// Get Mass from Kilograms. + /// + /// If value is NaN or Infinity. + public static Mass FromKilograms(QuantityValue kilograms) + { + double value = (double) kilograms; + return new Mass(value, MassUnit.Kilogram); + } + /// + /// Get Mass from Kilopounds. + /// + /// If value is NaN or Infinity. + public static Mass FromKilopounds(QuantityValue kilopounds) + { + double value = (double) kilopounds; + return new Mass(value, MassUnit.Kilopound); + } + /// + /// Get Mass from Kilotonnes. + /// + /// If value is NaN or Infinity. + public static Mass FromKilotonnes(QuantityValue kilotonnes) + { + double value = (double) kilotonnes; + return new Mass(value, MassUnit.Kilotonne); + } + /// + /// Get Mass from LongHundredweight. + /// + /// If value is NaN or Infinity. + public static Mass FromLongHundredweight(QuantityValue longhundredweight) + { + double value = (double) longhundredweight; + return new Mass(value, MassUnit.LongHundredweight); + } + /// + /// Get Mass from LongTons. + /// + /// If value is NaN or Infinity. + public static Mass FromLongTons(QuantityValue longtons) + { + double value = (double) longtons; + return new Mass(value, MassUnit.LongTon); + } + /// + /// Get Mass from Megapounds. + /// + /// If value is NaN or Infinity. + public static Mass FromMegapounds(QuantityValue megapounds) + { + double value = (double) megapounds; + return new Mass(value, MassUnit.Megapound); + } + /// + /// Get Mass from Megatonnes. + /// + /// If value is NaN or Infinity. + public static Mass FromMegatonnes(QuantityValue megatonnes) + { + double value = (double) megatonnes; + return new Mass(value, MassUnit.Megatonne); + } + /// + /// Get Mass from Micrograms. + /// + /// If value is NaN or Infinity. + public static Mass FromMicrograms(QuantityValue micrograms) + { + double value = (double) micrograms; + return new Mass(value, MassUnit.Microgram); + } + /// + /// Get Mass from Milligrams. + /// + /// If value is NaN or Infinity. + public static Mass FromMilligrams(QuantityValue milligrams) + { + double value = (double) milligrams; + return new Mass(value, MassUnit.Milligram); + } + /// + /// Get Mass from Nanograms. + /// + /// If value is NaN or Infinity. + public static Mass FromNanograms(QuantityValue nanograms) + { + double value = (double) nanograms; + return new Mass(value, MassUnit.Nanogram); + } + /// + /// Get Mass from Ounces. + /// + /// If value is NaN or Infinity. + public static Mass FromOunces(QuantityValue ounces) + { + double value = (double) ounces; + return new Mass(value, MassUnit.Ounce); + } + /// + /// Get Mass from Pounds. + /// + /// If value is NaN or Infinity. + public static Mass FromPounds(QuantityValue pounds) + { + double value = (double) pounds; + return new Mass(value, MassUnit.Pound); + } + /// + /// Get Mass from ShortHundredweight. + /// + /// If value is NaN or Infinity. + public static Mass FromShortHundredweight(QuantityValue shorthundredweight) + { + double value = (double) shorthundredweight; + return new Mass(value, MassUnit.ShortHundredweight); + } + /// + /// Get Mass from ShortTons. + /// + /// If value is NaN or Infinity. + public static Mass FromShortTons(QuantityValue shorttons) + { + double value = (double) shorttons; + return new Mass(value, MassUnit.ShortTon); + } + /// + /// Get Mass from Slugs. + /// + /// If value is NaN or Infinity. + public static Mass FromSlugs(QuantityValue slugs) + { + double value = (double) slugs; + return new Mass(value, MassUnit.Slug); + } + /// + /// Get Mass from Stone. + /// + /// If value is NaN or Infinity. + public static Mass FromStone(QuantityValue stone) + { + double value = (double) stone; + return new Mass(value, MassUnit.Stone); + } + /// + /// Get Mass from Tonnes. + /// + /// If value is NaN or Infinity. + public static Mass FromTonnes(QuantityValue tonnes) + { + 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. + public static Mass From(QuantityValue value, MassUnit fromUnit) + { + return new Mass((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Mass Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Mass result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Mass result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Mass operator -(Mass right) + { + return new Mass(-right.Value, right.Unit); + } + + public static Mass operator +(Mass left, Mass right) + { + return new Mass(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Mass operator -(Mass left, Mass right) + { + return new Mass(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Mass operator *(double left, Mass right) + { + return new Mass(left * right.Value, right.Unit); + } + + public static Mass operator *(Mass left, double right) + { + return new Mass(left.Value * right, left.Unit); + } + + public static Mass operator /(Mass left, double right) + { + return new Mass(left.Value / right, left.Unit); + } + + public static double operator /(Mass left, Mass right) + { + return left.Kilograms / right.Kilograms; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Mass left, Mass right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Mass left, Mass right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Mass left, Mass right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Mass left, Mass 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs new file mode 100644 index 0000000000..940552ccff --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs @@ -0,0 +1,856 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct MassFlow : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFlowUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. + /// + public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MassFlow; + + /// + /// All units of measurement for the MassFlow quantity. + /// + public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. + /// + public static MassFlow Zero => new MassFlow(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 MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 MegapoundsPerMinute. + /// + public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + + /// + /// 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 PoundsPerMinute. + /// + public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFlowUnit 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(MassFlowUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassFlow from CentigramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) + { + double value = (double) centigramspersecond; + return new MassFlow(value, MassFlowUnit.CentigramPerSecond); + } + /// + /// Get MassFlow from DecagramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) + { + double value = (double) decagramspersecond; + return new MassFlow(value, MassFlowUnit.DecagramPerSecond); + } + /// + /// Get MassFlow from DecigramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) + { + double value = (double) decigramspersecond; + return new MassFlow(value, MassFlowUnit.DecigramPerSecond); + } + /// + /// Get MassFlow from GramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) + { + double value = (double) gramspersecond; + return new MassFlow(value, MassFlowUnit.GramPerSecond); + } + /// + /// Get MassFlow from HectogramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) + { + double value = (double) hectogramspersecond; + return new MassFlow(value, MassFlowUnit.HectogramPerSecond); + } + /// + /// Get MassFlow from KilogramsPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) + { + double value = (double) kilogramsperhour; + return new MassFlow(value, MassFlowUnit.KilogramPerHour); + } + /// + /// Get MassFlow from KilogramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) + { + double value = (double) kilogramspersecond; + return new MassFlow(value, MassFlowUnit.KilogramPerSecond); + } + /// + /// Get MassFlow from MegapoundsPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) + { + double value = (double) megapoundsperhour; + return new MassFlow(value, MassFlowUnit.MegapoundPerHour); + } + /// + /// Get MassFlow from MegapoundsPerMinute. + /// + /// If value is NaN or Infinity. + public static MassFlow FromMegapoundsPerMinute(QuantityValue megapoundsperminute) + { + double value = (double) megapoundsperminute; + return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); + } + /// + /// Get MassFlow from MicrogramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) + { + double value = (double) microgramspersecond; + return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); + } + /// + /// Get MassFlow from MilligramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) + { + double value = (double) milligramspersecond; + return new MassFlow(value, MassFlowUnit.MilligramPerSecond); + } + /// + /// Get MassFlow from NanogramsPerSecond. + /// + /// If value is NaN or Infinity. + public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) + { + double value = (double) nanogramspersecond; + return new MassFlow(value, MassFlowUnit.NanogramPerSecond); + } + /// + /// Get MassFlow from PoundsPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) + { + double value = (double) poundsperhour; + return new MassFlow(value, MassFlowUnit.PoundPerHour); + } + /// + /// Get MassFlow from PoundsPerMinute. + /// + /// If value is NaN or Infinity. + public static MassFlow FromPoundsPerMinute(QuantityValue poundsperminute) + { + double value = (double) poundsperminute; + return new MassFlow(value, MassFlowUnit.PoundPerMinute); + } + /// + /// Get MassFlow from ShortTonsPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) + { + double value = (double) shorttonsperhour; + return new MassFlow(value, MassFlowUnit.ShortTonPerHour); + } + /// + /// Get MassFlow from TonnesPerDay. + /// + /// If value is NaN or Infinity. + public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) + { + double value = (double) tonnesperday; + return new MassFlow(value, MassFlowUnit.TonnePerDay); + } + /// + /// Get MassFlow from TonnesPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) + { + 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. + public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) + { + return new MassFlow((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MassFlow Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassFlow result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MassFlow result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassFlowUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassFlowUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MassFlow operator -(MassFlow right) + { + return new MassFlow(-right.Value, right.Unit); + } + + public static MassFlow operator +(MassFlow left, MassFlow right) + { + return new MassFlow(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MassFlow operator -(MassFlow left, MassFlow right) + { + return new MassFlow(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MassFlow operator *(double left, MassFlow right) + { + return new MassFlow(left * right.Value, right.Unit); + } + + public static MassFlow operator *(MassFlow left, double right) + { + return new MassFlow(left.Value * right, left.Unit); + } + + public static MassFlow operator /(MassFlow left, double right) + { + return new MassFlow(left.Value / right, left.Unit); + } + + public static double operator /(MassFlow left, MassFlow right) + { + return left.GramsPerSecond / right.GramsPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MassFlow left, MassFlow right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MassFlow left, MassFlow right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MassFlow left, MassFlow right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MassFlow left, MassFlow 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.MegapoundPerMinute: return (_value/0.132277) * 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.PoundPerMinute: return _value/0.132277; + 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.MegapoundPerMinute: return (baseUnitValue*0.132277) / 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.PoundPerMinute: return baseUnitValue*0.132277; + 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs new file mode 100644 index 0000000000..3e0c9b3650 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs @@ -0,0 +1,616 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Mass flux is the mass flow rate per unit area. + /// + public partial struct MassFlux : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFluxUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. + /// + public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MassFlux; + + /// + /// All units of measurement for the MassFlux quantity. + /// + public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. + /// + public static MassFlux Zero => new MassFlux(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 MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassFlux in GramsPerSecondPerSquareMeter. + /// + public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + + /// + /// Get MassFlux in KilogramsPerSecondPerSquareMeter. + /// + public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFluxUnit 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(MassFluxUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassFlux from GramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) + { + double value = (double) gramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); + } + /// + /// Get MassFlux from KilogramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) + { + 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. + public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) + { + return new MassFlux((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MassFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MassFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MassFlux operator -(MassFlux right) + { + return new MassFlux(-right.Value, right.Unit); + } + + public static MassFlux operator +(MassFlux left, MassFlux right) + { + return new MassFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MassFlux operator -(MassFlux left, MassFlux right) + { + return new MassFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MassFlux operator *(double left, MassFlux right) + { + return new MassFlux(left * right.Value, right.Unit); + } + + public static MassFlux operator *(MassFlux left, double right) + { + return new MassFlux(left.Value * right, left.Unit); + } + + public static MassFlux operator /(MassFlux left, double right) + { + return new MassFlux(left.Value / right, left.Unit); + } + + public static double operator /(MassFlux left, MassFlux right) + { + return left.KilogramsPerSecondPerSquareMeter / right.KilogramsPerSecondPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MassFlux left, MassFlux right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MassFlux left, MassFlux right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MassFlux left, MassFlux right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MassFlux left, MassFlux 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs new file mode 100644 index 0000000000..2f4abcf978 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs @@ -0,0 +1,1032 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// A property of body reflects how its mass is distributed with regard to an axis. + /// + public partial struct MassMomentOfInertia : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassMomentOfInertiaUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. + /// + public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MassMomentOfInertia; + + /// + /// All units of measurement for the MassMomentOfInertia quantity. + /// + public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. + /// + public static MassMomentOfInertia Zero => new MassMomentOfInertia(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 MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassMomentOfInertiaUnit 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(MassMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassMomentOfInertia from GramSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) + { + double value = (double) gramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from GramSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) + { + double value = (double) gramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from GramSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) + { + double value = (double) gramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); + } + /// + /// Get MassMomentOfInertia from GramSquareMillimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) + { + double value = (double) gramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) + { + double value = (double) kilogramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) + { + double value = (double) kilogramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) + { + double value = (double) kilogramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareMillimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) + { + double value = (double) kilogramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) + { + double value = (double) kilotonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) + { + double value = (double) kilotonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) + { + double value = (double) kilotonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) + { + double value = (double) kilotonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) + { + double value = (double) megatonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) + { + double value = (double) megatonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) + { + double value = (double) megatonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) + { + double value = (double) megatonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) + { + double value = (double) milligramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) + { + double value = (double) milligramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) + { + double value = (double) milligramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareMillimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) + { + double value = (double) milligramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from PoundSquareFeet. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) + { + double value = (double) poundsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); + } + /// + /// Get MassMomentOfInertia from PoundSquareInches. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) + { + double value = (double) poundsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); + } + /// + /// Get MassMomentOfInertia from SlugSquareFeet. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefeet) + { + double value = (double) slugsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); + } + /// + /// Get MassMomentOfInertia from SlugSquareInches. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquareinches) + { + double value = (double) slugsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); + } + /// + /// Get MassMomentOfInertia from TonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) + { + double value = (double) tonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) + { + double value = (double) tonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) + { + double value = (double) tonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) + { + 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. + public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) + { + return new MassMomentOfInertia((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MassMomentOfInertia Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MassMomentOfInertia result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MassMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MassMomentOfInertia operator -(MassMomentOfInertia right) + { + return new MassMomentOfInertia(-right.Value, right.Unit); + } + + public static MassMomentOfInertia operator +(MassMomentOfInertia left, MassMomentOfInertia right) + { + return new MassMomentOfInertia(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MassMomentOfInertia operator -(MassMomentOfInertia left, MassMomentOfInertia right) + { + return new MassMomentOfInertia(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MassMomentOfInertia operator *(double left, MassMomentOfInertia right) + { + return new MassMomentOfInertia(left * right.Value, right.Unit); + } + + public static MassMomentOfInertia operator *(MassMomentOfInertia left, double right) + { + return new MassMomentOfInertia(left.Value * right, left.Unit); + } + + public static MassMomentOfInertia operator /(MassMomentOfInertia left, double right) + { + return new MassMomentOfInertia(left.Value / right, left.Unit); + } + + public static double operator /(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.KilogramSquareMeters / right.KilogramSquareMeters; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MassMomentOfInertia left, MassMomentOfInertia 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs new file mode 100644 index 0000000000..00b21fdd99 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Molar energy is the amount of energy stored in 1 mole of a substance. + /// + public partial struct MolarEnergy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEnergyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. + /// + public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MolarEnergy; + + /// + /// All units of measurement for the MolarEnergy quantity. + /// + public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. + /// + public static MolarEnergy Zero => new MolarEnergy(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 MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarEnergyUnit 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(MolarEnergyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MolarEnergy from JoulesPerMole. + /// + /// If value is NaN or Infinity. + public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) + { + double value = (double) joulespermole; + return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); + } + /// + /// Get MolarEnergy from KilojoulesPerMole. + /// + /// If value is NaN or Infinity. + public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) + { + double value = (double) kilojoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); + } + /// + /// Get MolarEnergy from MegajoulesPerMole. + /// + /// If value is NaN or Infinity. + public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) + { + 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. + public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) + { + return new MolarEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MolarEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MolarEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MolarEnergy operator -(MolarEnergy right) + { + return new MolarEnergy(-right.Value, right.Unit); + } + + public static MolarEnergy operator +(MolarEnergy left, MolarEnergy right) + { + return new MolarEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MolarEnergy operator -(MolarEnergy left, MolarEnergy right) + { + return new MolarEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MolarEnergy operator *(double left, MolarEnergy right) + { + return new MolarEnergy(left * right.Value, right.Unit); + } + + public static MolarEnergy operator *(MolarEnergy left, double right) + { + return new MolarEnergy(left.Value * right, left.Unit); + } + + public static MolarEnergy operator /(MolarEnergy left, double right) + { + return new MolarEnergy(left.Value / right, left.Unit); + } + + public static double operator /(MolarEnergy left, MolarEnergy right) + { + return left.JoulesPerMole / right.JoulesPerMole; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MolarEnergy left, MolarEnergy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MolarEnergy left, MolarEnergy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MolarEnergy left, MolarEnergy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MolarEnergy left, MolarEnergy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs new file mode 100644 index 0000000000..5ef2ea0fe3 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. + /// + public partial struct MolarEntropy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEntropyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. + /// + public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MolarEntropy; + + /// + /// All units of measurement for the MolarEntropy quantity. + /// + public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. + /// + public static MolarEntropy Zero => new MolarEntropy(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 MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarEntropyUnit 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(MolarEntropyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MolarEntropy from JoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) + { + double value = (double) joulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from KilojoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) + { + double value = (double) kilojoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from MegajoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) + { + 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. + public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) + { + return new MolarEntropy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MolarEntropy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarEntropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MolarEntropy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarEntropyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MolarEntropy operator -(MolarEntropy right) + { + return new MolarEntropy(-right.Value, right.Unit); + } + + public static MolarEntropy operator +(MolarEntropy left, MolarEntropy right) + { + return new MolarEntropy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MolarEntropy operator -(MolarEntropy left, MolarEntropy right) + { + return new MolarEntropy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MolarEntropy operator *(double left, MolarEntropy right) + { + return new MolarEntropy(left * right.Value, right.Unit); + } + + public static MolarEntropy operator *(MolarEntropy left, double right) + { + return new MolarEntropy(left.Value * right, left.Unit); + } + + public static MolarEntropy operator /(MolarEntropy left, double right) + { + return new MolarEntropy(left.Value / right, left.Unit); + } + + public static double operator /(MolarEntropy left, MolarEntropy right) + { + return left.JoulesPerMoleKelvin / right.JoulesPerMoleKelvin; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MolarEntropy left, MolarEntropy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MolarEntropy left, MolarEntropy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MolarEntropy left, MolarEntropy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MolarEntropy left, MolarEntropy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs new file mode 100644 index 0000000000..8ff5fe548c --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs @@ -0,0 +1,776 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct MolarMass : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarMassUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. + /// + public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; + + /// + /// 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 static QuantityType QuantityType => QuantityType.MolarMass; + + /// + /// All units of measurement for the MolarMass quantity. + /// + public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. + /// + public static MolarMass Zero => new MolarMass(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 MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarMass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarMass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarMassUnit 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(MolarMassUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MolarMass from CentigramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) + { + double value = (double) centigramspermole; + return new MolarMass(value, MolarMassUnit.CentigramPerMole); + } + /// + /// Get MolarMass from DecagramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) + { + double value = (double) decagramspermole; + return new MolarMass(value, MolarMassUnit.DecagramPerMole); + } + /// + /// Get MolarMass from DecigramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) + { + double value = (double) decigramspermole; + return new MolarMass(value, MolarMassUnit.DecigramPerMole); + } + /// + /// Get MolarMass from GramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromGramsPerMole(QuantityValue gramspermole) + { + double value = (double) gramspermole; + return new MolarMass(value, MolarMassUnit.GramPerMole); + } + /// + /// Get MolarMass from HectogramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) + { + double value = (double) hectogramspermole; + return new MolarMass(value, MolarMassUnit.HectogramPerMole); + } + /// + /// Get MolarMass from KilogramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) + { + double value = (double) kilogramspermole; + return new MolarMass(value, MolarMassUnit.KilogramPerMole); + } + /// + /// Get MolarMass from KilopoundsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) + { + double value = (double) kilopoundspermole; + return new MolarMass(value, MolarMassUnit.KilopoundPerMole); + } + /// + /// Get MolarMass from MegapoundsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) + { + double value = (double) megapoundspermole; + return new MolarMass(value, MolarMassUnit.MegapoundPerMole); + } + /// + /// Get MolarMass from MicrogramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) + { + double value = (double) microgramspermole; + return new MolarMass(value, MolarMassUnit.MicrogramPerMole); + } + /// + /// Get MolarMass from MilligramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) + { + double value = (double) milligramspermole; + return new MolarMass(value, MolarMassUnit.MilligramPerMole); + } + /// + /// Get MolarMass from NanogramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) + { + double value = (double) nanogramspermole; + return new MolarMass(value, MolarMassUnit.NanogramPerMole); + } + /// + /// Get MolarMass from PoundsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) + { + 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. + public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) + { + return new MolarMass((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 MolarMass Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarMass result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 MolarMass result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarMassUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarMassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarMassUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static MolarMass operator -(MolarMass right) + { + return new MolarMass(-right.Value, right.Unit); + } + + public static MolarMass operator +(MolarMass left, MolarMass right) + { + return new MolarMass(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MolarMass operator -(MolarMass left, MolarMass right) + { + return new MolarMass(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static MolarMass operator *(double left, MolarMass right) + { + return new MolarMass(left * right.Value, right.Unit); + } + + public static MolarMass operator *(MolarMass left, double right) + { + return new MolarMass(left.Value * right, left.Unit); + } + + public static MolarMass operator /(MolarMass left, double right) + { + return new MolarMass(left.Value / right, left.Unit); + } + + public static double operator /(MolarMass left, MolarMass right) + { + return left.KilogramsPerMole / right.KilogramsPerMole; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(MolarMass left, MolarMass right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(MolarMass left, MolarMass right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(MolarMass left, MolarMass right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(MolarMass left, MolarMass 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs new file mode 100644 index 0000000000..adff096d47 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs @@ -0,0 +1,715 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Molar_concentration + /// + public partial struct Molarity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Molarity, which is MolesPerCubicMeter. All conversions go via this value. + /// + public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Molarity; + + /// + /// All units of measurement for the Molarity quantity. + /// + public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. + /// + public static Molarity Zero => new Molarity(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 MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Molarity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Molarity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarityUnit 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(MolarityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Molarity from CentimolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) + { + double value = (double) centimolesperliter; + return new Molarity(value, MolarityUnit.CentimolesPerLiter); + } + /// + /// Get Molarity from DecimolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) + { + double value = (double) decimolesperliter; + return new Molarity(value, MolarityUnit.DecimolesPerLiter); + } + /// + /// Get Molarity from MicromolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) + { + double value = (double) micromolesperliter; + return new Molarity(value, MolarityUnit.MicromolesPerLiter); + } + /// + /// Get Molarity from MillimolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) + { + double value = (double) millimolesperliter; + return new Molarity(value, MolarityUnit.MillimolesPerLiter); + } + /// + /// Get Molarity from MolesPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) + { + double value = (double) molespercubicmeter; + return new Molarity(value, MolarityUnit.MolesPerCubicMeter); + } + /// + /// Get Molarity from MolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMolesPerLiter(QuantityValue molesperliter) + { + double value = (double) molesperliter; + return new Molarity(value, MolarityUnit.MolesPerLiter); + } + /// + /// Get Molarity from NanomolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) + { + double value = (double) nanomolesperliter; + return new Molarity(value, MolarityUnit.NanomolesPerLiter); + } + /// + /// Get Molarity from PicomolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) + { + 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. + public static Molarity From(QuantityValue value, MolarityUnit fromUnit) + { + return new Molarity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Molarity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Molarity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Molarity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 MolarityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 MolarityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Molarity operator -(Molarity right) + { + return new Molarity(-right.Value, right.Unit); + } + + public static Molarity operator +(Molarity left, Molarity right) + { + return new Molarity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Molarity operator -(Molarity left, Molarity right) + { + return new Molarity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Molarity operator *(double left, Molarity right) + { + return new Molarity(left * right.Value, right.Unit); + } + + public static Molarity operator *(Molarity left, double right) + { + return new Molarity(left.Value * right, left.Unit); + } + + public static Molarity operator /(Molarity left, double right) + { + return new Molarity(left.Value / right, left.Unit); + } + + public static double operator /(Molarity left, Molarity right) + { + return left.MolesPerCubicMeter / right.MolesPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Molarity left, Molarity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Molarity left, Molarity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Molarity left, Molarity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Molarity left, Molarity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs new file mode 100644 index 0000000000..9717d459d4 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) + /// + public partial struct Permeability : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermeabilityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. + /// + public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Permeability; + + /// + /// All units of measurement for the Permeability quantity. + /// + public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. + /// + public static Permeability Zero => new Permeability(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 PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permeability.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permeability.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permeability in HenriesPerMeter. + /// + public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermeabilityUnit 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(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Permeability from HenriesPerMeter. + /// + /// If value is NaN or Infinity. + public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) + { + 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. + public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) + { + return new Permeability((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Permeability Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Permeability result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Permeability result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PermeabilityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PermeabilityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PermeabilityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Permeability operator -(Permeability right) + { + return new Permeability(-right.Value, right.Unit); + } + + public static Permeability operator +(Permeability left, Permeability right) + { + return new Permeability(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Permeability operator -(Permeability left, Permeability right) + { + return new Permeability(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Permeability operator *(double left, Permeability right) + { + return new Permeability(left * right.Value, right.Unit); + } + + public static Permeability operator *(Permeability left, double right) + { + return new Permeability(left.Value * right, left.Unit); + } + + public static Permeability operator /(Permeability left, double right) + { + return new Permeability(left.Value / right, left.Unit); + } + + public static double operator /(Permeability left, Permeability right) + { + return left.HenriesPerMeter / right.HenriesPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Permeability left, Permeability right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Permeability left, Permeability right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Permeability left, Permeability right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Permeability left, Permeability 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs new file mode 100644 index 0000000000..134e7e4745 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Permittivity + /// + public partial struct Permittivity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermittivityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. + /// + public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Permittivity; + + /// + /// All units of measurement for the Permittivity quantity. + /// + public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. + /// + public static Permittivity Zero => new Permittivity(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 PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permittivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permittivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permittivity in FaradsPerMeter. + /// + public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermittivityUnit 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(PermittivityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Permittivity from FaradsPerMeter. + /// + /// If value is NaN or Infinity. + public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) + { + 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. + public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) + { + return new Permittivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Permittivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Permittivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Permittivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PermittivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PermittivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PermittivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Permittivity operator -(Permittivity right) + { + return new Permittivity(-right.Value, right.Unit); + } + + public static Permittivity operator +(Permittivity left, Permittivity right) + { + return new Permittivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Permittivity operator -(Permittivity left, Permittivity right) + { + return new Permittivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Permittivity operator *(double left, Permittivity right) + { + return new Permittivity(left * right.Value, right.Unit); + } + + public static Permittivity operator *(Permittivity left, double right) + { + return new Permittivity(left.Value * right, left.Unit); + } + + public static Permittivity operator /(Permittivity left, double right) + { + return new Permittivity(left.Value / right, left.Unit); + } + + public static double operator /(Permittivity left, Permittivity right) + { + return left.FaradsPerMeter / right.FaradsPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Permittivity left, Permittivity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Permittivity left, Permittivity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Permittivity left, Permittivity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Permittivity left, Permittivity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs new file mode 100644 index 0000000000..43441207ae --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs @@ -0,0 +1,904 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Power : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Power, which is Watt. All conversions go via this value. + /// + public static PowerUnit BaseUnit => PowerUnit.Watt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Power; + + /// + /// All units of measurement for the Power quantity. + /// + public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Watt. + /// + public static Power Zero => new Power(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 PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Power.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Power.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerUnit 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(PowerUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Power from BoilerHorsepower. + /// + /// If value is NaN or Infinity. + public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) + { + decimal value = (decimal) boilerhorsepower; + return new Power(value, PowerUnit.BoilerHorsepower); + } + /// + /// Get Power from BritishThermalUnitsPerHour. + /// + /// If value is NaN or Infinity. + public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) + { + decimal value = (decimal) britishthermalunitsperhour; + return new Power(value, PowerUnit.BritishThermalUnitPerHour); + } + /// + /// Get Power from Decawatts. + /// + /// If value is NaN or Infinity. + public static Power FromDecawatts(QuantityValue decawatts) + { + decimal value = (decimal) decawatts; + return new Power(value, PowerUnit.Decawatt); + } + /// + /// Get Power from Deciwatts. + /// + /// If value is NaN or Infinity. + public static Power FromDeciwatts(QuantityValue deciwatts) + { + decimal value = (decimal) deciwatts; + return new Power(value, PowerUnit.Deciwatt); + } + /// + /// Get Power from ElectricalHorsepower. + /// + /// If value is NaN or Infinity. + public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) + { + decimal value = (decimal) electricalhorsepower; + return new Power(value, PowerUnit.ElectricalHorsepower); + } + /// + /// Get Power from Femtowatts. + /// + /// If value is NaN or Infinity. + public static Power FromFemtowatts(QuantityValue femtowatts) + { + decimal value = (decimal) femtowatts; + return new Power(value, PowerUnit.Femtowatt); + } + /// + /// Get Power from Gigawatts. + /// + /// If value is NaN or Infinity. + public static Power FromGigawatts(QuantityValue gigawatts) + { + decimal value = (decimal) gigawatts; + return new Power(value, PowerUnit.Gigawatt); + } + /// + /// Get Power from HydraulicHorsepower. + /// + /// If value is NaN or Infinity. + public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) + { + decimal value = (decimal) hydraulichorsepower; + return new Power(value, PowerUnit.HydraulicHorsepower); + } + /// + /// Get Power from KilobritishThermalUnitsPerHour. + /// + /// If value is NaN or Infinity. + public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) + { + decimal value = (decimal) kilobritishthermalunitsperhour; + return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); + } + /// + /// Get Power from Kilowatts. + /// + /// If value is NaN or Infinity. + public static Power FromKilowatts(QuantityValue kilowatts) + { + decimal value = (decimal) kilowatts; + return new Power(value, PowerUnit.Kilowatt); + } + /// + /// Get Power from MechanicalHorsepower. + /// + /// If value is NaN or Infinity. + public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) + { + decimal value = (decimal) mechanicalhorsepower; + return new Power(value, PowerUnit.MechanicalHorsepower); + } + /// + /// Get Power from Megawatts. + /// + /// If value is NaN or Infinity. + public static Power FromMegawatts(QuantityValue megawatts) + { + decimal value = (decimal) megawatts; + return new Power(value, PowerUnit.Megawatt); + } + /// + /// Get Power from MetricHorsepower. + /// + /// If value is NaN or Infinity. + public static Power FromMetricHorsepower(QuantityValue metrichorsepower) + { + decimal value = (decimal) metrichorsepower; + return new Power(value, PowerUnit.MetricHorsepower); + } + /// + /// Get Power from Microwatts. + /// + /// If value is NaN or Infinity. + public static Power FromMicrowatts(QuantityValue microwatts) + { + decimal value = (decimal) microwatts; + return new Power(value, PowerUnit.Microwatt); + } + /// + /// Get Power from Milliwatts. + /// + /// If value is NaN or Infinity. + public static Power FromMilliwatts(QuantityValue milliwatts) + { + decimal value = (decimal) milliwatts; + return new Power(value, PowerUnit.Milliwatt); + } + /// + /// Get Power from Nanowatts. + /// + /// If value is NaN or Infinity. + public static Power FromNanowatts(QuantityValue nanowatts) + { + decimal value = (decimal) nanowatts; + return new Power(value, PowerUnit.Nanowatt); + } + /// + /// Get Power from Petawatts. + /// + /// If value is NaN or Infinity. + public static Power FromPetawatts(QuantityValue petawatts) + { + decimal value = (decimal) petawatts; + return new Power(value, PowerUnit.Petawatt); + } + /// + /// Get Power from Picowatts. + /// + /// If value is NaN or Infinity. + public static Power FromPicowatts(QuantityValue picowatts) + { + decimal value = (decimal) picowatts; + return new Power(value, PowerUnit.Picowatt); + } + /// + /// Get Power from Terawatts. + /// + /// If value is NaN or Infinity. + public static Power FromTerawatts(QuantityValue terawatts) + { + decimal value = (decimal) terawatts; + return new Power(value, PowerUnit.Terawatt); + } + /// + /// Get Power from Watts. + /// + /// If value is NaN or Infinity. + public static Power FromWatts(QuantityValue watts) + { + 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. + public static Power From(QuantityValue value, PowerUnit fromUnit) + { + return new Power((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 Power Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Power Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Power result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Power result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PowerUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PowerUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Power operator -(Power right) + { + return new Power(-right.Value, right.Unit); + } + + public static Power operator +(Power left, Power right) + { + return new Power(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Power operator -(Power left, Power right) + { + return new Power(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Power operator *(decimal left, Power right) + { + return new Power(left * right.Value, right.Unit); + } + + public static Power operator *(Power left, decimal right) + { + return new Power(left.Value * right, left.Unit); + } + + public static Power operator /(Power left, decimal right) + { + return new Power(left.Value / right, left.Unit); + } + + public static double operator /(Power left, Power right) + { + return left.Watts / right.Watts; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Power left, Power right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Power left, Power right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Power left, Power right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Power left, Power 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs new file mode 100644 index 0000000000..470d8945ea --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs @@ -0,0 +1,1288 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The amount of power in a volume. + /// + public partial struct PowerDensity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerDensityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. + /// + public static PowerDensityUnit BaseUnit => PowerDensityUnit.WattPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.PowerDensity; + + /// + /// All units of measurement for the PowerDensity quantity. + /// + public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. + /// + public static PowerDensity Zero => new PowerDensity(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 PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerDensityUnit 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(PowerDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PowerDensity from DecawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattspercubicfoot) + { + double value = (double) decawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); + } + /// + /// Get PowerDensity from DecawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattspercubicinch) + { + double value = (double) decawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); + } + /// + /// Get PowerDensity from DecawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattspercubicmeter) + { + double value = (double) decawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); + } + /// + /// Get PowerDensity from DecawattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter) + { + double value = (double) decawattsperliter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); + } + /// + /// Get PowerDensity from DeciwattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattspercubicfoot) + { + double value = (double) deciwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); + } + /// + /// Get PowerDensity from DeciwattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattspercubicinch) + { + double value = (double) deciwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); + } + /// + /// Get PowerDensity from DeciwattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattspercubicmeter) + { + double value = (double) deciwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); + } + /// + /// Get PowerDensity from DeciwattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter) + { + double value = (double) deciwattsperliter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); + } + /// + /// Get PowerDensity from GigawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattspercubicfoot) + { + double value = (double) gigawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); + } + /// + /// Get PowerDensity from GigawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattspercubicinch) + { + double value = (double) gigawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); + } + /// + /// Get PowerDensity from GigawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattspercubicmeter) + { + double value = (double) gigawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); + } + /// + /// Get PowerDensity from GigawattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter) + { + double value = (double) gigawattsperliter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); + } + /// + /// Get PowerDensity from KilowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattspercubicfoot) + { + double value = (double) kilowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); + } + /// + /// Get PowerDensity from KilowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattspercubicinch) + { + double value = (double) kilowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); + } + /// + /// Get PowerDensity from KilowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattspercubicmeter) + { + double value = (double) kilowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); + } + /// + /// Get PowerDensity from KilowattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter) + { + double value = (double) kilowattsperliter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); + } + /// + /// Get PowerDensity from MegawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattspercubicfoot) + { + double value = (double) megawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); + } + /// + /// Get PowerDensity from MegawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattspercubicinch) + { + double value = (double) megawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); + } + /// + /// Get PowerDensity from MegawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattspercubicmeter) + { + double value = (double) megawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); + } + /// + /// Get PowerDensity from MegawattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter) + { + double value = (double) megawattsperliter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); + } + /// + /// Get PowerDensity from MicrowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspercubicfoot) + { + double value = (double) microwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); + } + /// + /// Get PowerDensity from MicrowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspercubicinch) + { + double value = (double) microwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); + } + /// + /// Get PowerDensity from MicrowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattspercubicmeter) + { + double value = (double) microwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); + } + /// + /// Get PowerDensity from MicrowattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperliter) + { + double value = (double) microwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); + } + /// + /// Get PowerDensity from MilliwattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspercubicfoot) + { + double value = (double) milliwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); + } + /// + /// Get PowerDensity from MilliwattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspercubicinch) + { + double value = (double) milliwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); + } + /// + /// Get PowerDensity from MilliwattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattspercubicmeter) + { + double value = (double) milliwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); + } + /// + /// Get PowerDensity from MilliwattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperliter) + { + double value = (double) milliwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); + } + /// + /// Get PowerDensity from NanowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattspercubicfoot) + { + double value = (double) nanowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); + } + /// + /// Get PowerDensity from NanowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattspercubicinch) + { + double value = (double) nanowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); + } + /// + /// Get PowerDensity from NanowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattspercubicmeter) + { + double value = (double) nanowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); + } + /// + /// Get PowerDensity from NanowattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter) + { + double value = (double) nanowattsperliter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); + } + /// + /// Get PowerDensity from PicowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattspercubicfoot) + { + double value = (double) picowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); + } + /// + /// Get PowerDensity from PicowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattspercubicinch) + { + double value = (double) picowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); + } + /// + /// Get PowerDensity from PicowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattspercubicmeter) + { + double value = (double) picowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); + } + /// + /// Get PowerDensity from PicowattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter) + { + double value = (double) picowattsperliter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); + } + /// + /// Get PowerDensity from TerawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattspercubicfoot) + { + double value = (double) terawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); + } + /// + /// Get PowerDensity from TerawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattspercubicinch) + { + double value = (double) terawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); + } + /// + /// Get PowerDensity from TerawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattspercubicmeter) + { + double value = (double) terawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); + } + /// + /// Get PowerDensity from TerawattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter) + { + double value = (double) terawattsperliter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); + } + /// + /// Get PowerDensity from WattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot) + { + double value = (double) wattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); + } + /// + /// Get PowerDensity from WattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch) + { + double value = (double) wattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); + } + /// + /// Get PowerDensity from WattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmeter) + { + double value = (double) wattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); + } + /// + /// Get PowerDensity from WattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) + { + 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. + public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) + { + return new PowerDensity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 PowerDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PowerDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 PowerDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PowerDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PowerDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static PowerDensity operator -(PowerDensity right) + { + return new PowerDensity(-right.Value, right.Unit); + } + + public static PowerDensity operator +(PowerDensity left, PowerDensity right) + { + return new PowerDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static PowerDensity operator -(PowerDensity left, PowerDensity right) + { + return new PowerDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static PowerDensity operator *(double left, PowerDensity right) + { + return new PowerDensity(left * right.Value, right.Unit); + } + + public static PowerDensity operator *(PowerDensity left, double right) + { + return new PowerDensity(left.Value * right, left.Unit); + } + + public static PowerDensity operator /(PowerDensity left, double right) + { + return new PowerDensity(left.Value / right, left.Unit); + } + + public static double operator /(PowerDensity left, PowerDensity right) + { + return left.WattsPerCubicMeter / right.WattsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(PowerDensity left, PowerDensity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(PowerDensity left, PowerDensity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(PowerDensity left, PowerDensity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(PowerDensity left, PowerDensity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs new file mode 100644 index 0000000000..ff7d700a7a --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs @@ -0,0 +1,624 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The strength of a signal expressed in decibels (dB) relative to one watt. + /// + public partial struct PowerRatio : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerRatioUnit? _unit; + + static PowerRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. + /// + public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.PowerRatio; + + /// + /// All units of measurement for the PowerRatio quantity. + /// + public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. + /// + public static PowerRatio Zero => new PowerRatio(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 PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PowerRatio in DecibelMilliwatts. + /// + public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + + /// + /// Get PowerRatio in DecibelWatts. + /// + public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerRatioUnit 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(PowerRatioUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PowerRatio from DecibelMilliwatts. + /// + /// If value is NaN or Infinity. + public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) + { + double value = (double) decibelmilliwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); + } + /// + /// Get PowerRatio from DecibelWatts. + /// + /// If value is NaN or Infinity. + public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) + { + 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. + public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) + { + return new PowerRatio((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 PowerRatio Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PowerRatio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 PowerRatio result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PowerRatioUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PowerRatioUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Logarithmic Arithmetic Operators + + public static PowerRatio operator -(PowerRatio right) + { + return new PowerRatio(-right.Value, right.Unit); + } + + public static PowerRatio operator +(PowerRatio left, PowerRatio right) + { + // Logarithmic addition + // Formula: 10*log10(10^(x/10) + 10^(y/10)) + return new PowerRatio(10*Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); + } + + public static PowerRatio operator -(PowerRatio left, PowerRatio right) + { + // Logarithmic subtraction + // Formula: 10*log10(10^(x/10) - 10^(y/10)) + return new PowerRatio(10*Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); + } + + public static PowerRatio operator *(double left, PowerRatio right) + { + // Logarithmic multiplication = addition + return new PowerRatio(left + right.Value, right.Unit); + } + + public static PowerRatio operator *(PowerRatio left, double right) + { + // Logarithmic multiplication = addition + return new PowerRatio(left.Value + (double)right, left.Unit); + } + + public static PowerRatio operator /(PowerRatio left, double right) + { + // Logarithmic division = subtraction + return new PowerRatio(left.Value - (double)right, left.Unit); + } + + public static double operator /(PowerRatio left, PowerRatio right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(PowerRatio left, PowerRatio right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(PowerRatio left, PowerRatio right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(PowerRatio left, PowerRatio right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(PowerRatio left, PowerRatio 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs new file mode 100644 index 0000000000..bb9c25858d --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs @@ -0,0 +1,1224 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct Pressure : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Pressure, which is Pascal. All conversions go via this value. + /// + public static PressureUnit BaseUnit => PressureUnit.Pascal; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Pressure; + + /// + /// All units of measurement for the Pressure quantity. + /// + public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. + /// + public static Pressure Zero => new Pressure(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 PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Pressure.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Pressure.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 DynesPerSquareCentimeter. + /// + public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + + /// + /// 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 Microbars. + /// + public double Microbars => As(PressureUnit.Microbar); + + /// + /// 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 PoundsPerInchSecondSquared. + /// + public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureUnit 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(PressureUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Pressure from Atmospheres. + /// + /// If value is NaN or Infinity. + public static Pressure FromAtmospheres(QuantityValue atmospheres) + { + double value = (double) atmospheres; + return new Pressure(value, PressureUnit.Atmosphere); + } + /// + /// Get Pressure from Bars. + /// + /// If value is NaN or Infinity. + public static Pressure FromBars(QuantityValue bars) + { + double value = (double) bars; + return new Pressure(value, PressureUnit.Bar); + } + /// + /// Get Pressure from Centibars. + /// + /// If value is NaN or Infinity. + public static Pressure FromCentibars(QuantityValue centibars) + { + double value = (double) centibars; + return new Pressure(value, PressureUnit.Centibar); + } + /// + /// Get Pressure from Decapascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromDecapascals(QuantityValue decapascals) + { + double value = (double) decapascals; + return new Pressure(value, PressureUnit.Decapascal); + } + /// + /// Get Pressure from Decibars. + /// + /// If value is NaN or Infinity. + public static Pressure FromDecibars(QuantityValue decibars) + { + double value = (double) decibars; + return new Pressure(value, PressureUnit.Decibar); + } + /// + /// Get Pressure from DynesPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromDynesPerSquareCentimeter(QuantityValue dynespersquarecentimeter) + { + double value = (double) dynespersquarecentimeter; + return new Pressure(value, PressureUnit.DynePerSquareCentimeter); + } + /// + /// Get Pressure from FeetOfHead. + /// + /// If value is NaN or Infinity. + public static Pressure FromFeetOfHead(QuantityValue feetofhead) + { + double value = (double) feetofhead; + return new Pressure(value, PressureUnit.FootOfHead); + } + /// + /// Get Pressure from Gigapascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromGigapascals(QuantityValue gigapascals) + { + double value = (double) gigapascals; + return new Pressure(value, PressureUnit.Gigapascal); + } + /// + /// Get Pressure from Hectopascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromHectopascals(QuantityValue hectopascals) + { + double value = (double) hectopascals; + return new Pressure(value, PressureUnit.Hectopascal); + } + /// + /// Get Pressure from InchesOfMercury. + /// + /// If value is NaN or Infinity. + public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) + { + double value = (double) inchesofmercury; + return new Pressure(value, PressureUnit.InchOfMercury); + } + /// + /// Get Pressure from Kilobars. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilobars(QuantityValue kilobars) + { + double value = (double) kilobars; + return new Pressure(value, PressureUnit.Kilobar); + } + /// + /// Get Pressure from KilogramsForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) + { + double value = (double) kilogramsforcepersquarecentimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); + } + /// + /// Get Pressure from KilogramsForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) + { + double value = (double) kilogramsforcepersquaremeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); + } + /// + /// Get Pressure from KilogramsForcePerSquareMillimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) + { + double value = (double) kilogramsforcepersquaremillimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) + { + double value = (double) kilonewtonspersquarecentimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) + { + double value = (double) kilonewtonspersquaremeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareMillimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) + { + double value = (double) kilonewtonspersquaremillimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); + } + /// + /// Get Pressure from Kilopascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilopascals(QuantityValue kilopascals) + { + double value = (double) kilopascals; + return new Pressure(value, PressureUnit.Kilopascal); + } + /// + /// Get Pressure from KilopoundsForcePerSquareFoot. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) + { + double value = (double) kilopoundsforcepersquarefoot; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); + } + /// + /// Get Pressure from KilopoundsForcePerSquareInch. + /// + /// If value is NaN or Infinity. + public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) + { + double value = (double) kilopoundsforcepersquareinch; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); + } + /// + /// Get Pressure from Megabars. + /// + /// If value is NaN or Infinity. + public static Pressure FromMegabars(QuantityValue megabars) + { + double value = (double) megabars; + return new Pressure(value, PressureUnit.Megabar); + } + /// + /// Get Pressure from MeganewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspersquaremeter) + { + double value = (double) meganewtonspersquaremeter; + return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); + } + /// + /// Get Pressure from Megapascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromMegapascals(QuantityValue megapascals) + { + double value = (double) megapascals; + return new Pressure(value, PressureUnit.Megapascal); + } + /// + /// Get Pressure from MetersOfHead. + /// + /// If value is NaN or Infinity. + public static Pressure FromMetersOfHead(QuantityValue metersofhead) + { + double value = (double) metersofhead; + return new Pressure(value, PressureUnit.MeterOfHead); + } + /// + /// Get Pressure from Microbars. + /// + /// If value is NaN or Infinity. + public static Pressure FromMicrobars(QuantityValue microbars) + { + double value = (double) microbars; + return new Pressure(value, PressureUnit.Microbar); + } + /// + /// Get Pressure from Micropascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromMicropascals(QuantityValue micropascals) + { + double value = (double) micropascals; + return new Pressure(value, PressureUnit.Micropascal); + } + /// + /// Get Pressure from Millibars. + /// + /// If value is NaN or Infinity. + public static Pressure FromMillibars(QuantityValue millibars) + { + double value = (double) millibars; + return new Pressure(value, PressureUnit.Millibar); + } + /// + /// Get Pressure from MillimetersOfMercury. + /// + /// If value is NaN or Infinity. + public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) + { + double value = (double) millimetersofmercury; + return new Pressure(value, PressureUnit.MillimeterOfMercury); + } + /// + /// Get Pressure from NewtonsPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) + { + double value = (double) newtonspersquarecentimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); + } + /// + /// Get Pressure from NewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) + { + double value = (double) newtonspersquaremeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMeter); + } + /// + /// Get Pressure from NewtonsPerSquareMillimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) + { + double value = (double) newtonspersquaremillimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); + } + /// + /// Get Pressure from Pascals. + /// + /// If value is NaN or Infinity. + public static Pressure FromPascals(QuantityValue pascals) + { + double value = (double) pascals; + return new Pressure(value, PressureUnit.Pascal); + } + /// + /// Get Pressure from PoundsForcePerSquareFoot. + /// + /// If value is NaN or Infinity. + public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) + { + double value = (double) poundsforcepersquarefoot; + return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); + } + /// + /// Get Pressure from PoundsForcePerSquareInch. + /// + /// If value is NaN or Infinity. + public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) + { + double value = (double) poundsforcepersquareinch; + return new Pressure(value, PressureUnit.PoundForcePerSquareInch); + } + /// + /// Get Pressure from PoundsPerInchSecondSquared. + /// + /// If value is NaN or Infinity. + public static Pressure FromPoundsPerInchSecondSquared(QuantityValue poundsperinchsecondsquared) + { + double value = (double) poundsperinchsecondsquared; + return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); + } + /// + /// Get Pressure from TechnicalAtmospheres. + /// + /// If value is NaN or Infinity. + public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) + { + double value = (double) technicalatmospheres; + return new Pressure(value, PressureUnit.TechnicalAtmosphere); + } + /// + /// Get Pressure from TonnesForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) + { + double value = (double) tonnesforcepersquarecentimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) + { + double value = (double) tonnesforcepersquaremeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMillimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) + { + double value = (double) tonnesforcepersquaremillimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); + } + /// + /// Get Pressure from Torrs. + /// + /// If value is NaN or Infinity. + public static Pressure FromTorrs(QuantityValue torrs) + { + 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. + public static Pressure From(QuantityValue value, PressureUnit fromUnit) + { + return new Pressure((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Pressure Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Pressure result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Pressure result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PressureUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PressureUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PressureUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Pressure operator -(Pressure right) + { + return new Pressure(-right.Value, right.Unit); + } + + public static Pressure operator +(Pressure left, Pressure right) + { + return new Pressure(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Pressure operator -(Pressure left, Pressure right) + { + return new Pressure(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Pressure operator *(double left, Pressure right) + { + return new Pressure(left * right.Value, right.Unit); + } + + public static Pressure operator *(Pressure left, double right) + { + return new Pressure(left.Value * right, left.Unit); + } + + public static Pressure operator /(Pressure left, double right) + { + return new Pressure(left.Value / right, left.Unit); + } + + public static double operator /(Pressure left, Pressure right) + { + return left.Pascals / right.Pascals; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Pressure left, Pressure right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Pressure left, Pressure right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Pressure left, Pressure right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Pressure left, Pressure 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.DynePerSquareCentimeter: return _value*1.0e-1; + 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.Microbar: return (_value*1e5) * 1e-6d; + 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.PoundPerInchSecondSquared: return _value*1.785796732283465e1; + 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.DynePerSquareCentimeter: return baseUnitValue/1.0e-1; + 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.Microbar: return (baseUnitValue/1e5) / 1e-6d; + 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.PoundPerInchSecondSquared: return baseUnitValue/1.785796732283465e1; + 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs new file mode 100644 index 0000000000..4fc0a607da --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs @@ -0,0 +1,648 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct PressureChangeRate : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureChangeRateUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. + /// + public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.PressureChangeRate; + + /// + /// All units of measurement for the PressureChangeRate quantity. + /// + public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. + /// + public static PressureChangeRate Zero => new PressureChangeRate(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 PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PressureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureChangeRateUnit 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(PressureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PressureChangeRate from AtmospheresPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) + { + double value = (double) atmospherespersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); + } + /// + /// Get PressureChangeRate from KilopascalsPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) + { + double value = (double) kilopascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); + } + /// + /// Get PressureChangeRate from MegapascalsPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) + { + double value = (double) megapascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); + } + /// + /// Get PressureChangeRate from PascalsPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) + { + 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. + public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) + { + return new PressureChangeRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 PressureChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PressureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 PressureChangeRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 PressureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 PressureChangeRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static PressureChangeRate operator -(PressureChangeRate right) + { + return new PressureChangeRate(-right.Value, right.Unit); + } + + public static PressureChangeRate operator +(PressureChangeRate left, PressureChangeRate right) + { + return new PressureChangeRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static PressureChangeRate operator -(PressureChangeRate left, PressureChangeRate right) + { + return new PressureChangeRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static PressureChangeRate operator *(double left, PressureChangeRate right) + { + return new PressureChangeRate(left * right.Value, right.Unit); + } + + public static PressureChangeRate operator *(PressureChangeRate left, double right) + { + return new PressureChangeRate(left.Value * right, left.Unit); + } + + public static PressureChangeRate operator /(PressureChangeRate left, double right) + { + return new PressureChangeRate(left.Value / right, left.Unit); + } + + public static double operator /(PressureChangeRate left, PressureChangeRate right) + { + return left.PascalsPerSecond / right.PascalsPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(PressureChangeRate left, PressureChangeRate right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(PressureChangeRate left, PressureChangeRate right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(PressureChangeRate left, PressureChangeRate right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(PressureChangeRate left, PressureChangeRate 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs new file mode 100644 index 0000000000..4a462f93b7 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs @@ -0,0 +1,680 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct Ratio : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RatioUnit? _unit; + + static Ratio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. + /// + public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Ratio; + + /// + /// All units of measurement for the Ratio quantity. + /// + public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// + public static Ratio Zero => new Ratio(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 RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Ratio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Ratio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RatioUnit 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(RatioUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Ratio from DecimalFractions. + /// + /// If value is NaN or Infinity. + public static Ratio FromDecimalFractions(QuantityValue decimalfractions) + { + double value = (double) decimalfractions; + return new Ratio(value, RatioUnit.DecimalFraction); + } + /// + /// Get Ratio from PartsPerBillion. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) + { + double value = (double) partsperbillion; + return new Ratio(value, RatioUnit.PartPerBillion); + } + /// + /// Get Ratio from PartsPerMillion. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerMillion(QuantityValue partspermillion) + { + double value = (double) partspermillion; + return new Ratio(value, RatioUnit.PartPerMillion); + } + /// + /// Get Ratio from PartsPerThousand. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) + { + double value = (double) partsperthousand; + return new Ratio(value, RatioUnit.PartPerThousand); + } + /// + /// Get Ratio from PartsPerTrillion. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) + { + double value = (double) partspertrillion; + return new Ratio(value, RatioUnit.PartPerTrillion); + } + /// + /// Get Ratio from Percent. + /// + /// If value is NaN or Infinity. + public static Ratio FromPercent(QuantityValue percent) + { + 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. + public static Ratio From(QuantityValue value, RatioUnit fromUnit) + { + return new Ratio((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Ratio Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Ratio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Ratio result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RatioUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RatioUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Ratio operator -(Ratio right) + { + return new Ratio(-right.Value, right.Unit); + } + + public static Ratio operator +(Ratio left, Ratio right) + { + return new Ratio(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Ratio operator -(Ratio left, Ratio right) + { + return new Ratio(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Ratio operator *(double left, Ratio right) + { + return new Ratio(left * right.Value, right.Unit); + } + + public static Ratio operator *(Ratio left, double right) + { + return new Ratio(left.Value * right, left.Unit); + } + + public static Ratio operator /(Ratio left, double right) + { + return new Ratio(left.Value / right, left.Unit); + } + + public static double operator /(Ratio left, Ratio right) + { + return left.DecimalFractions / right.DecimalFractions; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Ratio left, Ratio right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Ratio left, Ratio right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Ratio left, Ratio right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Ratio left, Ratio 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs new file mode 100644 index 0000000000..6e45a16399 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ReactiveEnergy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactiveEnergyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. + /// + public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ReactiveEnergy; + + /// + /// All units of measurement for the ReactiveEnergy quantity. + /// + public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. + /// + public static ReactiveEnergy Zero => new ReactiveEnergy(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 ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactiveEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ReactiveEnergyUnit 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(ReactiveEnergyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ReactiveEnergy from KilovoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) + { + double value = (double) kilovoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from MegavoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) + { + double value = (double) megavoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from VoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) + { + 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. + public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) + { + return new ReactiveEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ReactiveEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ReactiveEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ReactiveEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ReactiveEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ReactiveEnergy operator -(ReactiveEnergy right) + { + return new ReactiveEnergy(-right.Value, right.Unit); + } + + public static ReactiveEnergy operator +(ReactiveEnergy left, ReactiveEnergy right) + { + return new ReactiveEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ReactiveEnergy operator -(ReactiveEnergy left, ReactiveEnergy right) + { + return new ReactiveEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ReactiveEnergy operator *(double left, ReactiveEnergy right) + { + return new ReactiveEnergy(left * right.Value, right.Unit); + } + + public static ReactiveEnergy operator *(ReactiveEnergy left, double right) + { + return new ReactiveEnergy(left.Value * right, left.Unit); + } + + public static ReactiveEnergy operator /(ReactiveEnergy left, double right) + { + return new ReactiveEnergy(left.Value / right, left.Unit); + } + + public static double operator /(ReactiveEnergy left, ReactiveEnergy right) + { + return left.VoltampereReactiveHours / right.VoltampereReactiveHours; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ReactiveEnergy left, ReactiveEnergy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs new file mode 100644 index 0000000000..7cb2597718 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs @@ -0,0 +1,648 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct ReactivePower : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactivePowerUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. + /// + public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ReactivePower; + + /// + /// All units of measurement for the ReactivePower quantity. + /// + public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. + /// + public static ReactivePower Zero => new ReactivePower(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 ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactivePower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactivePower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ReactivePowerUnit 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(ReactivePowerUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ReactivePower from GigavoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) + { + double value = (double) gigavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); + } + /// + /// Get ReactivePower from KilovoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) + { + double value = (double) kilovoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); + } + /// + /// Get ReactivePower from MegavoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) + { + double value = (double) megavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); + } + /// + /// Get ReactivePower from VoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) + { + 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. + public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) + { + return new ReactivePower((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ReactivePower Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ReactivePower result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ReactivePower result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ReactivePowerUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ReactivePowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ReactivePowerUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ReactivePower operator -(ReactivePower right) + { + return new ReactivePower(-right.Value, right.Unit); + } + + public static ReactivePower operator +(ReactivePower left, ReactivePower right) + { + return new ReactivePower(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ReactivePower operator -(ReactivePower left, ReactivePower right) + { + return new ReactivePower(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ReactivePower operator *(double left, ReactivePower right) + { + return new ReactivePower(left * right.Value, right.Unit); + } + + public static ReactivePower operator *(ReactivePower left, double right) + { + return new ReactivePower(left.Value * right, left.Unit); + } + + public static ReactivePower operator /(ReactivePower left, double right) + { + return new ReactivePower(left.Value / right, left.Unit); + } + + public static double operator /(ReactivePower left, ReactivePower right) + { + return left.VoltamperesReactive / right.VoltamperesReactive; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ReactivePower left, ReactivePower right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ReactivePower left, ReactivePower right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ReactivePower left, ReactivePower right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ReactivePower left, ReactivePower 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs new file mode 100644 index 0000000000..fa98eebef2 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Angular acceleration is the rate of change of rotational speed. + /// + public partial struct RotationalAcceleration : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalAccelerationUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. + /// + public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalAcceleration; + + /// + /// All units of measurement for the RotationalAcceleration quantity. + /// + public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. + /// + public static RotationalAcceleration Zero => new RotationalAcceleration(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 RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalAcceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalAccelerationUnit 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(RotationalAccelerationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalAcceleration from DegreesPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) + { + double value = (double) degreespersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); + } + /// + /// Get RotationalAcceleration from RadiansPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) + { + double value = (double) radianspersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); + } + /// + /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) + { + 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. + public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) + { + return new RotationalAcceleration((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalAcceleration Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalAcceleration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalAcceleration result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalAccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalAccelerationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static RotationalAcceleration operator -(RotationalAcceleration right) + { + return new RotationalAcceleration(-right.Value, right.Unit); + } + + public static RotationalAcceleration operator +(RotationalAcceleration left, RotationalAcceleration right) + { + return new RotationalAcceleration(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalAcceleration operator -(RotationalAcceleration left, RotationalAcceleration right) + { + return new RotationalAcceleration(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalAcceleration operator *(double left, RotationalAcceleration right) + { + return new RotationalAcceleration(left * right.Value, right.Unit); + } + + public static RotationalAcceleration operator *(RotationalAcceleration left, double right) + { + return new RotationalAcceleration(left.Value * right, left.Unit); + } + + public static RotationalAcceleration operator /(RotationalAcceleration left, double right) + { + return new RotationalAcceleration(left.Value / right, left.Unit); + } + + public static double operator /(RotationalAcceleration left, RotationalAcceleration right) + { + return left.RadiansPerSecondSquared / right.RadiansPerSecondSquared; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(RotationalAcceleration left, RotationalAcceleration 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs new file mode 100644 index 0000000000..1c5a6bca8d --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs @@ -0,0 +1,792 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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"). + /// + public partial struct RotationalSpeed : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalSpeedUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. + /// + public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalSpeed; + + /// + /// All units of measurement for the RotationalSpeed quantity. + /// + public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. + /// + public static RotationalSpeed Zero => new RotationalSpeed(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 RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalSpeed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalSpeedUnit 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(RotationalSpeedUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalSpeed from CentiradiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) + { + double value = (double) centiradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); + } + /// + /// Get RotationalSpeed from DeciradiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) + { + double value = (double) deciradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); + } + /// + /// Get RotationalSpeed from DegreesPerMinute. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) + { + double value = (double) degreesperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); + } + /// + /// Get RotationalSpeed from DegreesPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) + { + double value = (double) degreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); + } + /// + /// Get RotationalSpeed from MicrodegreesPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) + { + double value = (double) microdegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); + } + /// + /// Get RotationalSpeed from MicroradiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) + { + double value = (double) microradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); + } + /// + /// Get RotationalSpeed from MillidegreesPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) + { + double value = (double) millidegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); + } + /// + /// Get RotationalSpeed from MilliradiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) + { + double value = (double) milliradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); + } + /// + /// Get RotationalSpeed from NanodegreesPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) + { + double value = (double) nanodegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); + } + /// + /// Get RotationalSpeed from NanoradiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) + { + double value = (double) nanoradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); + } + /// + /// Get RotationalSpeed from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) + { + double value = (double) radianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); + } + /// + /// Get RotationalSpeed from RevolutionsPerMinute. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) + { + double value = (double) revolutionsperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); + } + /// + /// Get RotationalSpeed from RevolutionsPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) + { + 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. + public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) + { + return new RotationalSpeed((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalSpeed Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalSpeed result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalSpeedUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalSpeedUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static RotationalSpeed operator -(RotationalSpeed right) + { + return new RotationalSpeed(-right.Value, right.Unit); + } + + public static RotationalSpeed operator +(RotationalSpeed left, RotationalSpeed right) + { + return new RotationalSpeed(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalSpeed operator -(RotationalSpeed left, RotationalSpeed right) + { + return new RotationalSpeed(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalSpeed operator *(double left, RotationalSpeed right) + { + return new RotationalSpeed(left * right.Value, right.Unit); + } + + public static RotationalSpeed operator *(RotationalSpeed left, double right) + { + return new RotationalSpeed(left.Value * right, left.Unit); + } + + public static RotationalSpeed operator /(RotationalSpeed left, double right) + { + return new RotationalSpeed(left.Value / right, left.Unit); + } + + public static double operator /(RotationalSpeed left, RotationalSpeed right) + { + return left.RadiansPerSecond / right.RadiansPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(RotationalSpeed left, RotationalSpeed right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(RotationalSpeed left, RotationalSpeed right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(RotationalSpeed left, RotationalSpeed right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(RotationalSpeed left, RotationalSpeed 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs new file mode 100644 index 0000000000..621019cb7e --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness + /// + public partial struct RotationalStiffness : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. + /// + public static RotationalStiffnessUnit BaseUnit => RotationalStiffnessUnit.NewtonMeterPerRadian; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalStiffness; + + /// + /// All units of measurement for the RotationalStiffness quantity. + /// + public static RotationalStiffnessUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. + /// + public static RotationalStiffness Zero => new RotationalStiffness(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 RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffness.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalStiffnessUnit 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(RotationalStiffnessUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalStiffness from KilonewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue kilonewtonmetersperradian) + { + double value = (double) kilonewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from MeganewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue meganewtonmetersperradian) + { + double value = (double) meganewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from NewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newtonmetersperradian) + { + 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. + public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) + { + return new RotationalStiffness((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalStiffness Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalStiffness result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalStiffness result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalStiffnessUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalStiffnessUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static RotationalStiffness operator -(RotationalStiffness right) + { + return new RotationalStiffness(-right.Value, right.Unit); + } + + public static RotationalStiffness operator +(RotationalStiffness left, RotationalStiffness right) + { + return new RotationalStiffness(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalStiffness operator -(RotationalStiffness left, RotationalStiffness right) + { + return new RotationalStiffness(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalStiffness operator *(double left, RotationalStiffness right) + { + return new RotationalStiffness(left * right.Value, right.Unit); + } + + public static RotationalStiffness operator *(RotationalStiffness left, double right) + { + return new RotationalStiffness(left.Value * right, left.Unit); + } + + public static RotationalStiffness operator /(RotationalStiffness left, double right) + { + return new RotationalStiffness(left.Value / right, left.Unit); + } + + public static double operator /(RotationalStiffness left, RotationalStiffness right) + { + return left.NewtonMetersPerRadian / right.NewtonMetersPerRadian; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(RotationalStiffness left, RotationalStiffness right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(RotationalStiffness left, RotationalStiffness right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(RotationalStiffness left, RotationalStiffness right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(RotationalStiffness left, RotationalStiffness 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs new file mode 100644 index 0000000000..e8684b1465 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs @@ -0,0 +1,632 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness + /// + public partial struct RotationalStiffnessPerLength : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessPerLengthUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. + /// + public static RotationalStiffnessPerLengthUnit BaseUnit => RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.RotationalStiffnessPerLength; + + /// + /// All units of measurement for the RotationalStiffnessPerLength quantity. + /// + public static RotationalStiffnessPerLengthUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. + /// + public static RotationalStiffnessPerLength Zero => new RotationalStiffnessPerLength(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 RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffnessPerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit 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(RotationalStiffnessPerLengthUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalStiffnessPerLength from KilonewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue kilonewtonmetersperradianpermeter) + { + double value = (double) kilonewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from MeganewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue meganewtonmetersperradianpermeter) + { + double value = (double) meganewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from NewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue newtonmetersperradianpermeter) + { + 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. + public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) + { + return new RotationalStiffnessPerLength((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 RotationalStiffnessPerLength Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalStiffnessPerLength result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 RotationalStiffnessPerLength result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 RotationalStiffnessPerLengthUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static RotationalStiffnessPerLength operator -(RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(-right.Value, right.Unit); + } + + public static RotationalStiffnessPerLength operator +(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalStiffnessPerLength operator -(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static RotationalStiffnessPerLength operator *(double left, RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(left * right.Value, right.Unit); + } + + public static RotationalStiffnessPerLength operator *(RotationalStiffnessPerLength left, double right) + { + return new RotationalStiffnessPerLength(left.Value * right, left.Unit); + } + + public static RotationalStiffnessPerLength operator /(RotationalStiffnessPerLength left, double right) + { + return new RotationalStiffnessPerLength(left.Value / right, left.Unit); + } + + public static double operator /(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.NewtonMetersPerRadianPerMeter / right.NewtonMetersPerRadianPerMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(RotationalStiffnessPerLength left, RotationalStiffnessPerLength 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs new file mode 100644 index 0000000000..dbaac8e546 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs @@ -0,0 +1,603 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + /// + /// https://en.wikipedia.org/wiki/Solid_angle + /// + public partial struct SolidAngle : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SolidAngleUnit? _unit; + + static SolidAngle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. + /// + public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SolidAngle; + + /// + /// All units of measurement for the SolidAngle quantity. + /// + public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. + /// + public static SolidAngle Zero => new SolidAngle(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 SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SolidAngle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SolidAngle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SolidAngle in Steradians. + /// + public double Steradians => As(SolidAngleUnit.Steradian); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SolidAngleUnit 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(SolidAngleUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SolidAngle from Steradians. + /// + /// If value is NaN or Infinity. + public static SolidAngle FromSteradians(QuantityValue steradians) + { + 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. + public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) + { + return new SolidAngle((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SolidAngle Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SolidAngle result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SolidAngle result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SolidAngleUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SolidAngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SolidAngleUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static SolidAngle operator -(SolidAngle right) + { + return new SolidAngle(-right.Value, right.Unit); + } + + public static SolidAngle operator +(SolidAngle left, SolidAngle right) + { + return new SolidAngle(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SolidAngle operator -(SolidAngle left, SolidAngle right) + { + return new SolidAngle(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SolidAngle operator *(double left, SolidAngle right) + { + return new SolidAngle(left * right.Value, right.Unit); + } + + public static SolidAngle operator *(SolidAngle left, double right) + { + return new SolidAngle(left.Value * right, left.Unit); + } + + public static SolidAngle operator /(SolidAngle left, double right) + { + return new SolidAngle(left.Value / right, left.Unit); + } + + public static double operator /(SolidAngle left, SolidAngle right) + { + return left.Steradians / right.Steradians; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(SolidAngle left, SolidAngle right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(SolidAngle left, SolidAngle right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(SolidAngle left, SolidAngle right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(SolidAngle left, SolidAngle 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs new file mode 100644 index 0000000000..e62ab6fd6d --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs @@ -0,0 +1,715 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The SpecificEnergy + /// + /// + /// https://en.wikipedia.org/wiki/Specific_energy + /// + public partial struct SpecificEnergy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificEnergyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. + /// + public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificEnergy; + + /// + /// All units of measurement for the SpecificEnergy quantity. + /// + public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. + /// + public static SpecificEnergy Zero => new SpecificEnergy(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 SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificEnergyUnit 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(SpecificEnergyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificEnergy from CaloriesPerGram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) + { + double value = (double) caloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); + } + /// + /// Get SpecificEnergy from JoulesPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) + { + double value = (double) joulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilocaloriesPerGram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) + { + double value = (double) kilocaloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); + } + /// + /// Get SpecificEnergy from KilojoulesPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) + { + double value = (double) kilojoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilowattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) + { + double value = (double) kilowatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); + } + /// + /// Get SpecificEnergy from MegajoulesPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) + { + double value = (double) megajoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); + } + /// + /// Get SpecificEnergy from MegawattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) + { + double value = (double) megawatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); + } + /// + /// Get SpecificEnergy from WattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) + { + 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. + public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) + { + return new SpecificEnergy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static SpecificEnergy operator -(SpecificEnergy right) + { + return new SpecificEnergy(-right.Value, right.Unit); + } + + public static SpecificEnergy operator +(SpecificEnergy left, SpecificEnergy right) + { + return new SpecificEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificEnergy operator -(SpecificEnergy left, SpecificEnergy right) + { + return new SpecificEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificEnergy operator *(double left, SpecificEnergy right) + { + return new SpecificEnergy(left * right.Value, right.Unit); + } + + public static SpecificEnergy operator *(SpecificEnergy left, double right) + { + return new SpecificEnergy(left.Value * right, left.Unit); + } + + public static SpecificEnergy operator /(SpecificEnergy left, double right) + { + return new SpecificEnergy(left.Value / right, left.Unit); + } + + public static double operator /(SpecificEnergy left, SpecificEnergy right) + { + return left.JoulesPerKilogram / right.JoulesPerKilogram; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(SpecificEnergy left, SpecificEnergy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(SpecificEnergy left, SpecificEnergy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(SpecificEnergy left, SpecificEnergy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(SpecificEnergy left, SpecificEnergy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs new file mode 100644 index 0000000000..e5b949a084 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs @@ -0,0 +1,712 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct SpecificEntropy : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificEntropyUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. + /// + public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificEntropy; + + /// + /// All units of measurement for the SpecificEntropy quantity. + /// + public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. + /// + public static SpecificEntropy Zero => new SpecificEntropy(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 SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificEntropyUnit 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(SpecificEntropyUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificEntropy from CaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) + { + double value = (double) caloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) + { + double value = (double) joulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from JoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) + { + double value = (double) joulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from KilocaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) + { + double value = (double) kilocaloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) + { + double value = (double) kilojoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) + { + double value = (double) kilojoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) + { + double value = (double) megajoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) + { + 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. + public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) + { + return new SpecificEntropy((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificEntropy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificEntropy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificEntropyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static SpecificEntropy operator -(SpecificEntropy right) + { + return new SpecificEntropy(-right.Value, right.Unit); + } + + public static SpecificEntropy operator +(SpecificEntropy left, SpecificEntropy right) + { + return new SpecificEntropy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificEntropy operator -(SpecificEntropy left, SpecificEntropy right) + { + return new SpecificEntropy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificEntropy operator *(double left, SpecificEntropy right) + { + return new SpecificEntropy(left * right.Value, right.Unit); + } + + public static SpecificEntropy operator *(SpecificEntropy left, double right) + { + return new SpecificEntropy(left.Value * right, left.Unit); + } + + public static SpecificEntropy operator /(SpecificEntropy left, double right) + { + return new SpecificEntropy(left.Value / right, left.Unit); + } + + public static double operator /(SpecificEntropy left, SpecificEntropy right) + { + return left.JoulesPerKilogramKelvin / right.JoulesPerKilogramKelvin; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(SpecificEntropy left, SpecificEntropy right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(SpecificEntropy left, SpecificEntropy right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(SpecificEntropy left, SpecificEntropy right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(SpecificEntropy left, SpecificEntropy 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs new file mode 100644 index 0000000000..fe365194bb --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs @@ -0,0 +1,616 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct SpecificVolume : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificVolumeUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. + /// + public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificVolume; + + /// + /// All units of measurement for the SpecificVolume quantity. + /// + public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. + /// + public static SpecificVolume Zero => new SpecificVolume(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 SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificVolume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificVolume in CubicFeetPerPound. + /// + public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + + /// + /// Get SpecificVolume in CubicMetersPerKilogram. + /// + public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificVolumeUnit 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(SpecificVolumeUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificVolume from CubicFeetPerPound. + /// + /// If value is NaN or Infinity. + public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpound) + { + double value = (double) cubicfeetperpound; + return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); + } + /// + /// Get SpecificVolume from CubicMetersPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) + { + 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. + public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) + { + return new SpecificVolume((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificVolume Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificVolume result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificVolume result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificVolumeUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificVolumeUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static SpecificVolume operator -(SpecificVolume right) + { + return new SpecificVolume(-right.Value, right.Unit); + } + + public static SpecificVolume operator +(SpecificVolume left, SpecificVolume right) + { + return new SpecificVolume(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificVolume operator -(SpecificVolume left, SpecificVolume right) + { + return new SpecificVolume(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificVolume operator *(double left, SpecificVolume right) + { + return new SpecificVolume(left * right.Value, right.Unit); + } + + public static SpecificVolume operator *(SpecificVolume left, double right) + { + return new SpecificVolume(left.Value * right, left.Unit); + } + + public static SpecificVolume operator /(SpecificVolume left, double right) + { + return new SpecificVolume(left.Value / right, left.Unit); + } + + public static double operator /(SpecificVolume left, SpecificVolume right) + { + return left.CubicMetersPerKilogram / right.CubicMetersPerKilogram; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(SpecificVolume left, SpecificVolume right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(SpecificVolume left, SpecificVolume right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(SpecificVolume left, SpecificVolume right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(SpecificVolume left, SpecificVolume 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs new file mode 100644 index 0000000000..9a751b0820 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs @@ -0,0 +1,859 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. + /// + /// + /// http://en.wikipedia.org/wiki/Specificweight + /// + public partial struct SpecificWeight : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificWeightUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. + /// + public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.SpecificWeight; + + /// + /// All units of measurement for the SpecificWeight quantity. + /// + public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. + /// + public static SpecificWeight Zero => new SpecificWeight(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 SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificWeight.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificWeightUnit 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(SpecificWeightUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) + { + double value = (double) kilogramsforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from KilogramsForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) + { + double value = (double) kilogramsforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); + } + /// + /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) + { + double value = (double) kilogramsforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) + { + double value = (double) kilonewtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) + { + double value = (double) kilonewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) + { + double value = (double) kilonewtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from KilopoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) + { + double value = (double) kilopoundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from KilopoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) + { + double value = (double) kilopoundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); + } + /// + /// Get SpecificWeight from MeganewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewtonspercubicmeter) + { + double value = (double) meganewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) + { + double value = (double) newtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) + { + double value = (double) newtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) + { + double value = (double) newtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) + { + double value = (double) poundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) + { + double value = (double) poundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) + { + double value = (double) tonnesforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) + { + double value = (double) tonnesforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) + { + 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. + public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) + { + return new SpecificWeight((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 SpecificWeight Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificWeight result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 SpecificWeight result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpecificWeightUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificWeightUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpecificWeightUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static SpecificWeight operator -(SpecificWeight right) + { + return new SpecificWeight(-right.Value, right.Unit); + } + + public static SpecificWeight operator +(SpecificWeight left, SpecificWeight right) + { + return new SpecificWeight(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificWeight operator -(SpecificWeight left, SpecificWeight right) + { + return new SpecificWeight(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static SpecificWeight operator *(double left, SpecificWeight right) + { + return new SpecificWeight(left * right.Value, right.Unit); + } + + public static SpecificWeight operator *(SpecificWeight left, double right) + { + return new SpecificWeight(left.Value * right, left.Unit); + } + + public static SpecificWeight operator /(SpecificWeight left, double right) + { + return new SpecificWeight(left.Value / right, left.Unit); + } + + public static double operator /(SpecificWeight left, SpecificWeight right) + { + return left.NewtonsPerCubicMeter / right.NewtonsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(SpecificWeight left, SpecificWeight right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(SpecificWeight left, SpecificWeight right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(SpecificWeight left, SpecificWeight right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(SpecificWeight left, SpecificWeight 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs new file mode 100644 index 0000000000..319cd59327 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs @@ -0,0 +1,1096 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Speed : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpeedUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. + /// + public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Speed; + + /// + /// All units of measurement for the Speed quantity. + /// + public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. + /// + public static Speed Zero => new Speed(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 SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Speed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Speed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpeedUnit 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(SpeedUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Speed from CentimetersPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) + { + double value = (double) centimetersperhour; + return new Speed(value, SpeedUnit.CentimeterPerHour); + } + /// + /// Get Speed from CentimetersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) + { + double value = (double) centimetersperminutes; + return new Speed(value, SpeedUnit.CentimeterPerMinute); + } + /// + /// Get Speed from CentimetersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) + { + double value = (double) centimeterspersecond; + return new Speed(value, SpeedUnit.CentimeterPerSecond); + } + /// + /// Get Speed from DecimetersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) + { + double value = (double) decimetersperminutes; + return new Speed(value, SpeedUnit.DecimeterPerMinute); + } + /// + /// Get Speed from DecimetersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) + { + double value = (double) decimeterspersecond; + return new Speed(value, SpeedUnit.DecimeterPerSecond); + } + /// + /// Get Speed from FeetPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromFeetPerHour(QuantityValue feetperhour) + { + double value = (double) feetperhour; + return new Speed(value, SpeedUnit.FootPerHour); + } + /// + /// Get Speed from FeetPerMinute. + /// + /// If value is NaN or Infinity. + public static Speed FromFeetPerMinute(QuantityValue feetperminute) + { + double value = (double) feetperminute; + return new Speed(value, SpeedUnit.FootPerMinute); + } + /// + /// Get Speed from FeetPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromFeetPerSecond(QuantityValue feetpersecond) + { + double value = (double) feetpersecond; + return new Speed(value, SpeedUnit.FootPerSecond); + } + /// + /// Get Speed from InchesPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromInchesPerHour(QuantityValue inchesperhour) + { + double value = (double) inchesperhour; + return new Speed(value, SpeedUnit.InchPerHour); + } + /// + /// Get Speed from InchesPerMinute. + /// + /// If value is NaN or Infinity. + public static Speed FromInchesPerMinute(QuantityValue inchesperminute) + { + double value = (double) inchesperminute; + return new Speed(value, SpeedUnit.InchPerMinute); + } + /// + /// Get Speed from InchesPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromInchesPerSecond(QuantityValue inchespersecond) + { + double value = (double) inchespersecond; + return new Speed(value, SpeedUnit.InchPerSecond); + } + /// + /// Get Speed from KilometersPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) + { + double value = (double) kilometersperhour; + return new Speed(value, SpeedUnit.KilometerPerHour); + } + /// + /// Get Speed from KilometersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) + { + double value = (double) kilometersperminutes; + return new Speed(value, SpeedUnit.KilometerPerMinute); + } + /// + /// Get Speed from KilometersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) + { + double value = (double) kilometerspersecond; + return new Speed(value, SpeedUnit.KilometerPerSecond); + } + /// + /// Get Speed from Knots. + /// + /// If value is NaN or Infinity. + public static Speed FromKnots(QuantityValue knots) + { + double value = (double) knots; + return new Speed(value, SpeedUnit.Knot); + } + /// + /// Get Speed from MetersPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromMetersPerHour(QuantityValue metersperhour) + { + double value = (double) metersperhour; + return new Speed(value, SpeedUnit.MeterPerHour); + } + /// + /// Get Speed from MetersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) + { + double value = (double) metersperminutes; + return new Speed(value, SpeedUnit.MeterPerMinute); + } + /// + /// Get Speed from MetersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromMetersPerSecond(QuantityValue meterspersecond) + { + double value = (double) meterspersecond; + return new Speed(value, SpeedUnit.MeterPerSecond); + } + /// + /// Get Speed from MicrometersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) + { + double value = (double) micrometersperminutes; + return new Speed(value, SpeedUnit.MicrometerPerMinute); + } + /// + /// Get Speed from MicrometersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) + { + double value = (double) micrometerspersecond; + return new Speed(value, SpeedUnit.MicrometerPerSecond); + } + /// + /// Get Speed from MilesPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromMilesPerHour(QuantityValue milesperhour) + { + double value = (double) milesperhour; + return new Speed(value, SpeedUnit.MilePerHour); + } + /// + /// Get Speed from MillimetersPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) + { + double value = (double) millimetersperhour; + return new Speed(value, SpeedUnit.MillimeterPerHour); + } + /// + /// Get Speed from MillimetersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) + { + double value = (double) millimetersperminutes; + return new Speed(value, SpeedUnit.MillimeterPerMinute); + } + /// + /// Get Speed from MillimetersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) + { + double value = (double) millimeterspersecond; + return new Speed(value, SpeedUnit.MillimeterPerSecond); + } + /// + /// Get Speed from NanometersPerMinutes. + /// + /// If value is NaN or Infinity. + public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) + { + double value = (double) nanometersperminutes; + return new Speed(value, SpeedUnit.NanometerPerMinute); + } + /// + /// Get Speed from NanometersPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) + { + double value = (double) nanometerspersecond; + return new Speed(value, SpeedUnit.NanometerPerSecond); + } + /// + /// Get Speed from UsSurveyFeetPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) + { + double value = (double) ussurveyfeetperhour; + return new Speed(value, SpeedUnit.UsSurveyFootPerHour); + } + /// + /// Get Speed from UsSurveyFeetPerMinute. + /// + /// If value is NaN or Infinity. + public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) + { + double value = (double) ussurveyfeetperminute; + return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); + } + /// + /// Get Speed from UsSurveyFeetPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) + { + double value = (double) ussurveyfeetpersecond; + return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); + } + /// + /// Get Speed from YardsPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromYardsPerHour(QuantityValue yardsperhour) + { + double value = (double) yardsperhour; + return new Speed(value, SpeedUnit.YardPerHour); + } + /// + /// Get Speed from YardsPerMinute. + /// + /// If value is NaN or Infinity. + public static Speed FromYardsPerMinute(QuantityValue yardsperminute) + { + double value = (double) yardsperminute; + return new Speed(value, SpeedUnit.YardPerMinute); + } + /// + /// Get Speed from YardsPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromYardsPerSecond(QuantityValue yardspersecond) + { + 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. + public static Speed From(QuantityValue value, SpeedUnit fromUnit) + { + return new Speed((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Speed Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Speed result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Speed result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 SpeedUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 SpeedUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Speed operator -(Speed right) + { + return new Speed(-right.Value, right.Unit); + } + + public static Speed operator +(Speed left, Speed right) + { + return new Speed(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Speed operator -(Speed left, Speed right) + { + return new Speed(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Speed operator *(double left, Speed right) + { + return new Speed(left * right.Value, right.Unit); + } + + public static Speed operator *(Speed left, double right) + { + return new Speed(left.Value * right, left.Unit); + } + + public static Speed operator /(Speed left, double right) + { + return new Speed(left.Value / right, left.Unit); + } + + public static double operator /(Speed left, Speed right) + { + return left.MetersPerSecond / right.MetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Speed left, Speed right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Speed left, Speed right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Speed left, Speed right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Speed left, Speed 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs new file mode 100644 index 0000000000..354a364071 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs @@ -0,0 +1,673 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Temperature : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Temperature, which is Kelvin. All conversions go via this value. + /// + public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Temperature; + + /// + /// All units of measurement for the Temperature quantity. + /// + public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static Temperature Zero => new Temperature(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 TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Temperature.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Temperature.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureUnit 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(TemperatureUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Temperature from DegreesCelsius. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) + { + double value = (double) degreescelsius; + return new Temperature(value, TemperatureUnit.DegreeCelsius); + } + /// + /// Get Temperature from DegreesDelisle. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) + { + double value = (double) degreesdelisle; + return new Temperature(value, TemperatureUnit.DegreeDelisle); + } + /// + /// Get Temperature from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new Temperature(value, TemperatureUnit.DegreeFahrenheit); + } + /// + /// Get Temperature from DegreesNewton. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesNewton(QuantityValue degreesnewton) + { + double value = (double) degreesnewton; + return new Temperature(value, TemperatureUnit.DegreeNewton); + } + /// + /// Get Temperature from DegreesRankine. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesRankine(QuantityValue degreesrankine) + { + double value = (double) degreesrankine; + return new Temperature(value, TemperatureUnit.DegreeRankine); + } + /// + /// Get Temperature from DegreesReaumur. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) + { + double value = (double) degreesreaumur; + return new Temperature(value, TemperatureUnit.DegreeReaumur); + } + /// + /// Get Temperature from DegreesRoemer. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) + { + double value = (double) degreesroemer; + return new Temperature(value, TemperatureUnit.DegreeRoemer); + } + /// + /// Get Temperature from Kelvins. + /// + /// If value is NaN or Infinity. + public static Temperature FromKelvins(QuantityValue kelvins) + { + 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. + public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) + { + return new Temperature((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Temperature Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Temperature result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Temperature result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TemperatureUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TemperatureUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Temperature left, Temperature right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Temperature left, Temperature right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Temperature left, Temperature right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Temperature left, Temperature 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs new file mode 100644 index 0000000000..b9bb26d9ed --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs @@ -0,0 +1,744 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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). + /// + public partial struct TemperatureChangeRate : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureChangeRateUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. + /// + public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.TemperatureChangeRate; + + /// + /// All units of measurement for the TemperatureChangeRate quantity. + /// + public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. + /// + public static TemperatureChangeRate Zero => new TemperatureChangeRate(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 TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureChangeRateUnit 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(TemperatureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) + { + double value = (double) centidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) + { + double value = (double) decadegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) + { + double value = (double) decidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) + { + double value = (double) degreescelsiusperminute; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + } + /// + /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) + { + double value = (double) degreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) + { + double value = (double) hectodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) + { + double value = (double) kilodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) + { + double value = (double) microdegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) + { + double value = (double) millidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) + { + 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. + public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) + { + return new TemperatureChangeRate((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 TemperatureChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 TemperatureChangeRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TemperatureChangeRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static TemperatureChangeRate operator -(TemperatureChangeRate right) + { + return new TemperatureChangeRate(-right.Value, right.Unit); + } + + public static TemperatureChangeRate operator +(TemperatureChangeRate left, TemperatureChangeRate right) + { + return new TemperatureChangeRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static TemperatureChangeRate operator -(TemperatureChangeRate left, TemperatureChangeRate right) + { + return new TemperatureChangeRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static TemperatureChangeRate operator *(double left, TemperatureChangeRate right) + { + return new TemperatureChangeRate(left * right.Value, right.Unit); + } + + public static TemperatureChangeRate operator *(TemperatureChangeRate left, double right) + { + return new TemperatureChangeRate(left.Value * right, left.Unit); + } + + public static TemperatureChangeRate operator /(TemperatureChangeRate left, double right) + { + return new TemperatureChangeRate(left.Value / right, left.Unit); + } + + public static double operator /(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.DegreesCelsiusPerSecond / right.DegreesCelsiusPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(TemperatureChangeRate left, TemperatureChangeRate 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs new file mode 100644 index 0000000000..3b482dcc03 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs @@ -0,0 +1,712 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Difference between two temperatures. The conversions are different than for Temperature. + /// + public partial struct TemperatureDelta : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureDeltaUnit? _unit; + + static TemperatureDelta() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. + /// + public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.TemperatureDelta; + + /// + /// All units of measurement for the TemperatureDelta quantity. + /// + public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static TemperatureDelta Zero => new TemperatureDelta(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 TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureDelta.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureDeltaUnit 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(TemperatureDeltaUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get TemperatureDelta from DegreesCelsius. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) + { + double value = (double) degreescelsius; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); + } + /// + /// Get TemperatureDelta from DegreesDelisle. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) + { + double value = (double) degreesdelisle; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); + } + /// + /// Get TemperatureDelta from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); + } + /// + /// Get TemperatureDelta from DegreesNewton. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) + { + double value = (double) degreesnewton; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); + } + /// + /// Get TemperatureDelta from DegreesRankine. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) + { + double value = (double) degreesrankine; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); + } + /// + /// Get TemperatureDelta from DegreesReaumur. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) + { + double value = (double) degreesreaumur; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); + } + /// + /// Get TemperatureDelta from DegreesRoemer. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) + { + double value = (double) degreesroemer; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); + } + /// + /// Get TemperatureDelta from Kelvins. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromKelvins(QuantityValue kelvins) + { + 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. + public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) + { + return new TemperatureDelta((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 TemperatureDelta Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out TemperatureDelta result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 TemperatureDelta result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TemperatureDeltaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TemperatureDeltaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static TemperatureDelta operator -(TemperatureDelta right) + { + return new TemperatureDelta(-right.Value, right.Unit); + } + + public static TemperatureDelta operator +(TemperatureDelta left, TemperatureDelta right) + { + return new TemperatureDelta(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static TemperatureDelta operator -(TemperatureDelta left, TemperatureDelta right) + { + return new TemperatureDelta(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static TemperatureDelta operator *(double left, TemperatureDelta right) + { + return new TemperatureDelta(left * right.Value, right.Unit); + } + + public static TemperatureDelta operator *(TemperatureDelta left, double right) + { + return new TemperatureDelta(left.Value * right, left.Unit); + } + + public static TemperatureDelta operator /(TemperatureDelta left, double right) + { + return new TemperatureDelta(left.Value / right, left.Unit); + } + + public static double operator /(TemperatureDelta left, TemperatureDelta right) + { + return left.Kelvins / right.Kelvins; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(TemperatureDelta left, TemperatureDelta right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(TemperatureDelta left, TemperatureDelta right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(TemperatureDelta left, TemperatureDelta right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(TemperatureDelta left, TemperatureDelta 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs new file mode 100644 index 0000000000..95b434ca49 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs @@ -0,0 +1,619 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Thermal conductivity is the property of a material to conduct heat. + /// + /// + /// https://en.wikipedia.org/wiki/Thermal_Conductivity + /// + public partial struct ThermalConductivity : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalConductivityUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. + /// + public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ThermalConductivity; + + /// + /// All units of measurement for the ThermalConductivity quantity. + /// + public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. + /// + public static ThermalConductivity Zero => new ThermalConductivity(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 ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ThermalConductivity in BtusPerHourFootFahrenheit. + /// + public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + + /// + /// Get ThermalConductivity in WattsPerMeterKelvin. + /// + public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalConductivityUnit 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(ThermalConductivityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalConductivity from BtusPerHourFootFahrenheit. + /// + /// If value is NaN or Infinity. + public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue btusperhourfootfahrenheit) + { + double value = (double) btusperhourfootfahrenheit; + return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); + } + /// + /// Get ThermalConductivity from WattsPerMeterKelvin. + /// + /// If value is NaN or Infinity. + public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) + { + 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. + public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) + { + return new ThermalConductivity((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ThermalConductivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ThermalConductivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ThermalConductivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ThermalConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ThermalConductivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ThermalConductivity operator -(ThermalConductivity right) + { + return new ThermalConductivity(-right.Value, right.Unit); + } + + public static ThermalConductivity operator +(ThermalConductivity left, ThermalConductivity right) + { + return new ThermalConductivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ThermalConductivity operator -(ThermalConductivity left, ThermalConductivity right) + { + return new ThermalConductivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ThermalConductivity operator *(double left, ThermalConductivity right) + { + return new ThermalConductivity(left * right.Value, right.Unit); + } + + public static ThermalConductivity operator *(ThermalConductivity left, double right) + { + return new ThermalConductivity(left.Value * right, left.Unit); + } + + public static ThermalConductivity operator /(ThermalConductivity left, double right) + { + return new ThermalConductivity(left.Value / right, left.Unit); + } + + public static double operator /(ThermalConductivity left, ThermalConductivity right) + { + return left.WattsPerMeterKelvin / right.WattsPerMeterKelvin; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ThermalConductivity left, ThermalConductivity right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ThermalConductivity left, ThermalConductivity right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ThermalConductivity left, ThermalConductivity right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ThermalConductivity left, ThermalConductivity 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs new file mode 100644 index 0000000000..ecb20bd412 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs @@ -0,0 +1,664 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// + /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. + /// + public partial struct ThermalResistance : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalResistanceUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. + /// + public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; + + /// + /// 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 static QuantityType QuantityType => QuantityType.ThermalResistance; + + /// + /// All units of measurement for the ThermalResistance quantity. + /// + public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. + /// + public static ThermalResistance Zero => new ThermalResistance(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 ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalResistanceUnit 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(ThermalResistanceUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) + { + double value = (double) hoursquarefeetdegreesfahrenheitperbtu; + return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + } + /// + /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) + { + double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + } + /// + /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) + { + double value = (double) squarecentimeterkelvinsperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + } + /// + /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) + { + double value = (double) squaremeterdegreescelsiusperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + } + /// + /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) + { + 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. + public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) + { + return new ThermalResistance((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 ThermalResistance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ThermalResistance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 ThermalResistance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 ThermalResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 ThermalResistanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static ThermalResistance operator -(ThermalResistance right) + { + return new ThermalResistance(-right.Value, right.Unit); + } + + public static ThermalResistance operator +(ThermalResistance left, ThermalResistance right) + { + return new ThermalResistance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ThermalResistance operator -(ThermalResistance left, ThermalResistance right) + { + return new ThermalResistance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static ThermalResistance operator *(double left, ThermalResistance right) + { + return new ThermalResistance(left * right.Value, right.Unit); + } + + public static ThermalResistance operator *(ThermalResistance left, double right) + { + return new ThermalResistance(left.Value * right, left.Unit); + } + + public static ThermalResistance operator /(ThermalResistance left, double right) + { + return new ThermalResistance(left.Value / right, left.Unit); + } + + public static double operator /(ThermalResistance left, ThermalResistance right) + { + return left.SquareMeterKelvinsPerKilowatt / right.SquareMeterKelvinsPerKilowatt; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(ThermalResistance left, ThermalResistance right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(ThermalResistance left, ThermalResistance right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(ThermalResistance left, ThermalResistance right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(ThermalResistance left, ThermalResistance 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs new file mode 100644 index 0000000000..1870282761 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs @@ -0,0 +1,920 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Torque : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TorqueUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. + /// + public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Torque; + + /// + /// All units of measurement for the Torque quantity. + /// + public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. + /// + public static Torque Zero => new Torque(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 TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Torque.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Torque.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TorqueUnit 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(TorqueUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Torque from KilogramForceCentimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) + { + double value = (double) kilogramforcecentimeters; + return new Torque(value, TorqueUnit.KilogramForceCentimeter); + } + /// + /// Get Torque from KilogramForceMeters. + /// + /// If value is NaN or Infinity. + public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) + { + double value = (double) kilogramforcemeters; + return new Torque(value, TorqueUnit.KilogramForceMeter); + } + /// + /// Get Torque from KilogramForceMillimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) + { + double value = (double) kilogramforcemillimeters; + return new Torque(value, TorqueUnit.KilogramForceMillimeter); + } + /// + /// Get Torque from KilonewtonCentimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) + { + double value = (double) kilonewtoncentimeters; + return new Torque(value, TorqueUnit.KilonewtonCentimeter); + } + /// + /// Get Torque from KilonewtonMeters. + /// + /// If value is NaN or Infinity. + public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) + { + double value = (double) kilonewtonmeters; + return new Torque(value, TorqueUnit.KilonewtonMeter); + } + /// + /// Get Torque from KilonewtonMillimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) + { + double value = (double) kilonewtonmillimeters; + return new Torque(value, TorqueUnit.KilonewtonMillimeter); + } + /// + /// Get Torque from KilopoundForceFeet. + /// + /// If value is NaN or Infinity. + public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) + { + double value = (double) kilopoundforcefeet; + return new Torque(value, TorqueUnit.KilopoundForceFoot); + } + /// + /// Get Torque from KilopoundForceInches. + /// + /// If value is NaN or Infinity. + public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) + { + double value = (double) kilopoundforceinches; + return new Torque(value, TorqueUnit.KilopoundForceInch); + } + /// + /// Get Torque from MeganewtonCentimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) + { + double value = (double) meganewtoncentimeters; + return new Torque(value, TorqueUnit.MeganewtonCentimeter); + } + /// + /// Get Torque from MeganewtonMeters. + /// + /// If value is NaN or Infinity. + public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) + { + double value = (double) meganewtonmeters; + return new Torque(value, TorqueUnit.MeganewtonMeter); + } + /// + /// Get Torque from MeganewtonMillimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) + { + double value = (double) meganewtonmillimeters; + return new Torque(value, TorqueUnit.MeganewtonMillimeter); + } + /// + /// Get Torque from MegapoundForceFeet. + /// + /// If value is NaN or Infinity. + public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) + { + double value = (double) megapoundforcefeet; + return new Torque(value, TorqueUnit.MegapoundForceFoot); + } + /// + /// Get Torque from MegapoundForceInches. + /// + /// If value is NaN or Infinity. + public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) + { + double value = (double) megapoundforceinches; + return new Torque(value, TorqueUnit.MegapoundForceInch); + } + /// + /// Get Torque from NewtonCentimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) + { + double value = (double) newtoncentimeters; + return new Torque(value, TorqueUnit.NewtonCentimeter); + } + /// + /// Get Torque from NewtonMeters. + /// + /// If value is NaN or Infinity. + public static Torque FromNewtonMeters(QuantityValue newtonmeters) + { + double value = (double) newtonmeters; + return new Torque(value, TorqueUnit.NewtonMeter); + } + /// + /// Get Torque from NewtonMillimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) + { + double value = (double) newtonmillimeters; + return new Torque(value, TorqueUnit.NewtonMillimeter); + } + /// + /// Get Torque from PoundForceFeet. + /// + /// If value is NaN or Infinity. + public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) + { + double value = (double) poundforcefeet; + return new Torque(value, TorqueUnit.PoundForceFoot); + } + /// + /// Get Torque from PoundForceInches. + /// + /// If value is NaN or Infinity. + public static Torque FromPoundForceInches(QuantityValue poundforceinches) + { + double value = (double) poundforceinches; + return new Torque(value, TorqueUnit.PoundForceInch); + } + /// + /// Get Torque from TonneForceCentimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) + { + double value = (double) tonneforcecentimeters; + return new Torque(value, TorqueUnit.TonneForceCentimeter); + } + /// + /// Get Torque from TonneForceMeters. + /// + /// If value is NaN or Infinity. + public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) + { + double value = (double) tonneforcemeters; + return new Torque(value, TorqueUnit.TonneForceMeter); + } + /// + /// Get Torque from TonneForceMillimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) + { + 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. + public static Torque From(QuantityValue value, TorqueUnit fromUnit) + { + return new Torque((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Torque Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Torque result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Torque result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 TorqueUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TorqueUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 TorqueUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Torque operator -(Torque right) + { + return new Torque(-right.Value, right.Unit); + } + + public static Torque operator +(Torque left, Torque right) + { + return new Torque(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Torque operator -(Torque left, Torque right) + { + return new Torque(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Torque operator *(double left, Torque right) + { + return new Torque(left * right.Value, right.Unit); + } + + public static Torque operator *(Torque left, double right) + { + return new Torque(left.Value * right, left.Unit); + } + + public static Torque operator /(Torque left, double right) + { + return new Torque(left.Value / right, left.Unit); + } + + public static double operator /(Torque left, Torque right) + { + return left.NewtonMeters / right.NewtonMeters; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Torque left, Torque right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Torque left, Torque right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Torque left, Torque right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Torque left, Torque 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs new file mode 100644 index 0000000000..25837bf80d --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs @@ -0,0 +1,600 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct VitaminA : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VitaminAUnit? _unit; + + static VitaminA() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// 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 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. + /// + public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; + + /// + /// 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 static QuantityType QuantityType => QuantityType.VitaminA; + + /// + /// All units of measurement for the VitaminA quantity. + /// + public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. + /// + public static VitaminA Zero => new VitaminA(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 VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VitaminA.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VitaminA.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get VitaminA in InternationalUnits. + /// + public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VitaminAUnit 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(VitaminAUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get VitaminA from InternationalUnits. + /// + /// If value is NaN or Infinity. + public static VitaminA FromInternationalUnits(QuantityValue internationalunits) + { + 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. + public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) + { + return new VitaminA((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 VitaminA Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out VitaminA result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 VitaminA result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 VitaminAUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VitaminAUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 VitaminAUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static VitaminA operator -(VitaminA right) + { + return new VitaminA(-right.Value, right.Unit); + } + + public static VitaminA operator +(VitaminA left, VitaminA right) + { + return new VitaminA(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static VitaminA operator -(VitaminA left, VitaminA right) + { + return new VitaminA(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static VitaminA operator *(double left, VitaminA right) + { + return new VitaminA(left * right.Value, right.Unit); + } + + public static VitaminA operator *(VitaminA left, double right) + { + return new VitaminA(left.Value * right, left.Unit); + } + + public static VitaminA operator /(VitaminA left, double right) + { + return new VitaminA(left.Value / right, left.Unit); + } + + public static double operator /(VitaminA left, VitaminA right) + { + return left.InternationalUnits / right.InternationalUnits; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(VitaminA left, VitaminA right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(VitaminA left, VitaminA right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(VitaminA left, VitaminA right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(VitaminA left, VitaminA 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs new file mode 100644 index 0000000000..f7fe76f379 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs @@ -0,0 +1,1272 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct Volume : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Volume, which is CubicMeter. All conversions go via this value. + /// + public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; + + /// + /// 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 static QuantityType QuantityType => QuantityType.Volume; + + /// + /// All units of measurement for the Volume quantity. + /// + public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. + /// + public static Volume Zero => new Volume(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 VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Volume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Volume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Kiloliters. + /// + public double Kiloliters => As(VolumeUnit.Kiloliter); + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeUnit 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(VolumeUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Volume from AuTablespoons. + /// + /// If value is NaN or Infinity. + public static Volume FromAuTablespoons(QuantityValue autablespoons) + { + double value = (double) autablespoons; + return new Volume(value, VolumeUnit.AuTablespoon); + } + /// + /// Get Volume from Centiliters. + /// + /// If value is NaN or Infinity. + public static Volume FromCentiliters(QuantityValue centiliters) + { + double value = (double) centiliters; + return new Volume(value, VolumeUnit.Centiliter); + } + /// + /// Get Volume from CubicCentimeters. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) + { + double value = (double) cubiccentimeters; + return new Volume(value, VolumeUnit.CubicCentimeter); + } + /// + /// Get Volume from CubicDecimeters. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) + { + double value = (double) cubicdecimeters; + return new Volume(value, VolumeUnit.CubicDecimeter); + } + /// + /// Get Volume from CubicFeet. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicFeet(QuantityValue cubicfeet) + { + double value = (double) cubicfeet; + return new Volume(value, VolumeUnit.CubicFoot); + } + /// + /// Get Volume from CubicInches. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicInches(QuantityValue cubicinches) + { + double value = (double) cubicinches; + return new Volume(value, VolumeUnit.CubicInch); + } + /// + /// Get Volume from CubicKilometers. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicKilometers(QuantityValue cubickilometers) + { + double value = (double) cubickilometers; + return new Volume(value, VolumeUnit.CubicKilometer); + } + /// + /// Get Volume from CubicMeters. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicMeters(QuantityValue cubicmeters) + { + double value = (double) cubicmeters; + return new Volume(value, VolumeUnit.CubicMeter); + } + /// + /// Get Volume from CubicMicrometers. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) + { + double value = (double) cubicmicrometers; + return new Volume(value, VolumeUnit.CubicMicrometer); + } + /// + /// Get Volume from CubicMiles. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicMiles(QuantityValue cubicmiles) + { + double value = (double) cubicmiles; + return new Volume(value, VolumeUnit.CubicMile); + } + /// + /// Get Volume from CubicMillimeters. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) + { + double value = (double) cubicmillimeters; + return new Volume(value, VolumeUnit.CubicMillimeter); + } + /// + /// Get Volume from CubicYards. + /// + /// If value is NaN or Infinity. + public static Volume FromCubicYards(QuantityValue cubicyards) + { + double value = (double) cubicyards; + return new Volume(value, VolumeUnit.CubicYard); + } + /// + /// Get Volume from Deciliters. + /// + /// If value is NaN or Infinity. + public static Volume FromDeciliters(QuantityValue deciliters) + { + double value = (double) deciliters; + return new Volume(value, VolumeUnit.Deciliter); + } + /// + /// Get Volume from HectocubicFeet. + /// + /// If value is NaN or Infinity. + public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) + { + double value = (double) hectocubicfeet; + return new Volume(value, VolumeUnit.HectocubicFoot); + } + /// + /// Get Volume from HectocubicMeters. + /// + /// If value is NaN or Infinity. + public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) + { + double value = (double) hectocubicmeters; + return new Volume(value, VolumeUnit.HectocubicMeter); + } + /// + /// Get Volume from Hectoliters. + /// + /// If value is NaN or Infinity. + public static Volume FromHectoliters(QuantityValue hectoliters) + { + double value = (double) hectoliters; + return new Volume(value, VolumeUnit.Hectoliter); + } + /// + /// Get Volume from ImperialBeerBarrels. + /// + /// If value is NaN or Infinity. + public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) + { + double value = (double) imperialbeerbarrels; + return new Volume(value, VolumeUnit.ImperialBeerBarrel); + } + /// + /// Get Volume from ImperialGallons. + /// + /// If value is NaN or Infinity. + public static Volume FromImperialGallons(QuantityValue imperialgallons) + { + double value = (double) imperialgallons; + return new Volume(value, VolumeUnit.ImperialGallon); + } + /// + /// Get Volume from ImperialOunces. + /// + /// If value is NaN or Infinity. + public static Volume FromImperialOunces(QuantityValue imperialounces) + { + double value = (double) imperialounces; + return new Volume(value, VolumeUnit.ImperialOunce); + } + /// + /// Get Volume from KilocubicFeet. + /// + /// If value is NaN or Infinity. + public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) + { + double value = (double) kilocubicfeet; + return new Volume(value, VolumeUnit.KilocubicFoot); + } + /// + /// Get Volume from KilocubicMeters. + /// + /// If value is NaN or Infinity. + public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) + { + double value = (double) kilocubicmeters; + return new Volume(value, VolumeUnit.KilocubicMeter); + } + /// + /// Get Volume from KiloimperialGallons. + /// + /// If value is NaN or Infinity. + public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) + { + double value = (double) kiloimperialgallons; + return new Volume(value, VolumeUnit.KiloimperialGallon); + } + /// + /// Get Volume from Kiloliters. + /// + /// If value is NaN or Infinity. + public static Volume FromKiloliters(QuantityValue kiloliters) + { + double value = (double) kiloliters; + return new Volume(value, VolumeUnit.Kiloliter); + } + /// + /// Get Volume from KilousGallons. + /// + /// If value is NaN or Infinity. + public static Volume FromKilousGallons(QuantityValue kilousgallons) + { + double value = (double) kilousgallons; + return new Volume(value, VolumeUnit.KilousGallon); + } + /// + /// Get Volume from Liters. + /// + /// If value is NaN or Infinity. + public static Volume FromLiters(QuantityValue liters) + { + double value = (double) liters; + return new Volume(value, VolumeUnit.Liter); + } + /// + /// Get Volume from MegacubicFeet. + /// + /// If value is NaN or Infinity. + public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) + { + double value = (double) megacubicfeet; + return new Volume(value, VolumeUnit.MegacubicFoot); + } + /// + /// Get Volume from MegaimperialGallons. + /// + /// If value is NaN or Infinity. + public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) + { + double value = (double) megaimperialgallons; + return new Volume(value, VolumeUnit.MegaimperialGallon); + } + /// + /// Get Volume from MegausGallons. + /// + /// If value is NaN or Infinity. + public static Volume FromMegausGallons(QuantityValue megausgallons) + { + double value = (double) megausgallons; + return new Volume(value, VolumeUnit.MegausGallon); + } + /// + /// Get Volume from MetricCups. + /// + /// If value is NaN or Infinity. + public static Volume FromMetricCups(QuantityValue metriccups) + { + double value = (double) metriccups; + return new Volume(value, VolumeUnit.MetricCup); + } + /// + /// Get Volume from MetricTeaspoons. + /// + /// If value is NaN or Infinity. + public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) + { + double value = (double) metricteaspoons; + return new Volume(value, VolumeUnit.MetricTeaspoon); + } + /// + /// Get Volume from Microliters. + /// + /// If value is NaN or Infinity. + public static Volume FromMicroliters(QuantityValue microliters) + { + double value = (double) microliters; + return new Volume(value, VolumeUnit.Microliter); + } + /// + /// Get Volume from Milliliters. + /// + /// If value is NaN or Infinity. + public static Volume FromMilliliters(QuantityValue milliliters) + { + double value = (double) milliliters; + return new Volume(value, VolumeUnit.Milliliter); + } + /// + /// Get Volume from OilBarrels. + /// + /// If value is NaN or Infinity. + public static Volume FromOilBarrels(QuantityValue oilbarrels) + { + double value = (double) oilbarrels; + return new Volume(value, VolumeUnit.OilBarrel); + } + /// + /// Get Volume from UkTablespoons. + /// + /// If value is NaN or Infinity. + public static Volume FromUkTablespoons(QuantityValue uktablespoons) + { + double value = (double) uktablespoons; + return new Volume(value, VolumeUnit.UkTablespoon); + } + /// + /// Get Volume from UsBeerBarrels. + /// + /// If value is NaN or Infinity. + public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) + { + double value = (double) usbeerbarrels; + return new Volume(value, VolumeUnit.UsBeerBarrel); + } + /// + /// Get Volume from UsCustomaryCups. + /// + /// If value is NaN or Infinity. + public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) + { + double value = (double) uscustomarycups; + return new Volume(value, VolumeUnit.UsCustomaryCup); + } + /// + /// Get Volume from UsGallons. + /// + /// If value is NaN or Infinity. + public static Volume FromUsGallons(QuantityValue usgallons) + { + double value = (double) usgallons; + return new Volume(value, VolumeUnit.UsGallon); + } + /// + /// Get Volume from UsLegalCups. + /// + /// If value is NaN or Infinity. + public static Volume FromUsLegalCups(QuantityValue uslegalcups) + { + double value = (double) uslegalcups; + return new Volume(value, VolumeUnit.UsLegalCup); + } + /// + /// Get Volume from UsOunces. + /// + /// If value is NaN or Infinity. + public static Volume FromUsOunces(QuantityValue usounces) + { + double value = (double) usounces; + return new Volume(value, VolumeUnit.UsOunce); + } + /// + /// Get Volume from UsPints. + /// + /// If value is NaN or Infinity. + public static Volume FromUsPints(QuantityValue uspints) + { + double value = (double) uspints; + return new Volume(value, VolumeUnit.UsPint); + } + /// + /// Get Volume from UsQuarts. + /// + /// If value is NaN or Infinity. + public static Volume FromUsQuarts(QuantityValue usquarts) + { + double value = (double) usquarts; + return new Volume(value, VolumeUnit.UsQuart); + } + /// + /// Get Volume from UsTablespoons. + /// + /// If value is NaN or Infinity. + public static Volume FromUsTablespoons(QuantityValue ustablespoons) + { + double value = (double) ustablespoons; + return new Volume(value, VolumeUnit.UsTablespoon); + } + /// + /// Get Volume from UsTeaspoons. + /// + /// If value is NaN or Infinity. + public static Volume FromUsTeaspoons(QuantityValue usteaspoons) + { + 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. + public static Volume From(QuantityValue value, VolumeUnit fromUnit) + { + return new Volume((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 Volume Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Volume result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 Volume result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 VolumeUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 VolumeUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static Volume operator -(Volume right) + { + return new Volume(-right.Value, right.Unit); + } + + public static Volume operator +(Volume left, Volume right) + { + return new Volume(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Volume operator -(Volume left, Volume right) + { + return new Volume(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static Volume operator *(double left, Volume right) + { + return new Volume(left * right.Value, right.Unit); + } + + public static Volume operator *(Volume left, double right) + { + return new Volume(left.Value * right, left.Unit); + } + + public static Volume operator /(Volume left, double right) + { + return new Volume(left.Value / right, left.Unit); + } + + public static double operator /(Volume left, Volume right) + { + return left.CubicMeters / right.CubicMeters; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Volume left, Volume right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Volume left, Volume right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Volume left, Volume right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Volume left, Volume 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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.Kiloliter: return (_value/1e3) * 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.Kiloliter: return (baseUnitValue*1e3) / 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs new file mode 100644 index 0000000000..4d4755793d --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs @@ -0,0 +1,1000 @@ +//------------------------------------------------------------------------------ +// +// 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 System.Linq; +using JetBrains.Annotations; +using UnitsNet.Units; +using UnitsNet.InternalHelpers; + +// 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. + /// + public partial struct VolumeFlow : IQuantity, IComparable, IComparable + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeFlowUnit? _unit; + + 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. + public 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 Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. + /// + public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; + + /// + /// 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 static QuantityType QuantityType => QuantityType.VolumeFlow; + + /// + /// All units of measurement for the VolumeFlow quantity. + /// + public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. + /// + public static VolumeFlow Zero => new VolumeFlow(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 VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VolumeFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// 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 Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeFlowUnit 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(VolumeFlowUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get VolumeFlow from CentilitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) + { + double value = (double) centilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); + } + /// + /// Get VolumeFlow from CubicDecimetersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) + { + double value = (double) cubicdecimetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); + } + /// + /// Get VolumeFlow from CubicFeetPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) + { + double value = (double) cubicfeetperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); + } + /// + /// Get VolumeFlow from CubicFeetPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) + { + double value = (double) cubicfeetperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); + } + /// + /// Get VolumeFlow from CubicFeetPerSecond. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) + { + double value = (double) cubicfeetpersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); + } + /// + /// Get VolumeFlow from CubicMetersPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) + { + double value = (double) cubicmetersperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); + } + /// + /// Get VolumeFlow from CubicMetersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) + { + double value = (double) cubicmetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); + } + /// + /// Get VolumeFlow from CubicMetersPerSecond. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) + { + double value = (double) cubicmeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); + } + /// + /// Get VolumeFlow from CubicYardsPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) + { + double value = (double) cubicyardsperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); + } + /// + /// Get VolumeFlow from CubicYardsPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) + { + double value = (double) cubicyardsperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); + } + /// + /// Get VolumeFlow from CubicYardsPerSecond. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) + { + double value = (double) cubicyardspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); + } + /// + /// Get VolumeFlow from DecilitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) + { + double value = (double) decilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); + } + /// + /// Get VolumeFlow from KilolitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) + { + double value = (double) kilolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); + } + /// + /// Get VolumeFlow from LitersPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) + { + double value = (double) litersperhour; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); + } + /// + /// Get VolumeFlow from LitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) + { + double value = (double) litersperminute; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); + } + /// + /// Get VolumeFlow from LitersPerSecond. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) + { + double value = (double) literspersecond; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); + } + /// + /// Get VolumeFlow from MicrolitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) + { + double value = (double) microlitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); + } + /// + /// Get VolumeFlow from MillilitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) + { + double value = (double) millilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); + } + /// + /// Get VolumeFlow from MillionUsGallonsPerDay. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) + { + double value = (double) millionusgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); + } + /// + /// Get VolumeFlow from NanolitersPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) + { + double value = (double) nanolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); + } + /// + /// Get VolumeFlow from OilBarrelsPerDay. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) + { + double value = (double) oilbarrelsperday; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); + } + /// + /// Get VolumeFlow from OilBarrelsPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) + { + double value = (double) oilbarrelsperhour; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); + } + /// + /// Get VolumeFlow from OilBarrelsPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminute) + { + double value = (double) oilbarrelsperminute; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) + { + double value = (double) usgallonsperhour; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); + } + /// + /// Get VolumeFlow from UsGallonsPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) + { + double value = (double) usgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerSecond. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) + { + 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. + public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) + { + return new VolumeFlow((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} + /// + /// 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 Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", 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 VolumeFlow Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out VolumeFlow result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", 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 VolumeFlow result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + 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 ParseUnit(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 VolumeFlowUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VolumeFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", 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 VolumeFlowUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + public static VolumeFlow operator -(VolumeFlow right) + { + return new VolumeFlow(-right.Value, right.Unit); + } + + public static VolumeFlow operator +(VolumeFlow left, VolumeFlow right) + { + return new VolumeFlow(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static VolumeFlow operator -(VolumeFlow left, VolumeFlow right) + { + return new VolumeFlow(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static VolumeFlow operator *(double left, VolumeFlow right) + { + return new VolumeFlow(left * right.Value, right.Unit); + } + + public static VolumeFlow operator *(VolumeFlow left, double right) + { + return new VolumeFlow(left.Value * right, left.Unit); + } + + public static VolumeFlow operator /(VolumeFlow left, double right) + { + return new VolumeFlow(left.Value / right, left.Unit); + } + + public static double operator /(VolumeFlow left, VolumeFlow right) + { + return left.CubicMetersPerSecond / right.CubicMetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(VolumeFlow left, VolumeFlow right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(VolumeFlow left, VolumeFlow right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(VolumeFlow left, VolumeFlow right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(VolumeFlow left, VolumeFlow 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 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 + public 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// 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 ToString Methods + + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) + { + return ToString(provider, 2); + } + + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + { + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); + } + + /// + /// Get string representation of value and unit. + /// + /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." + /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([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; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); + } + + #endregion + + } +} diff --git a/UnitsNet/UnitsNet.Common.props b/UnitsNet/UnitsNet.Common.props index 671889db65..27e56121ca 100644 --- a/UnitsNet/UnitsNet.Common.props +++ b/UnitsNet/UnitsNet.Common.props @@ -7,8 +7,6 @@ Units.NET Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested. Copyright (c) 2013 Andreas Gullberg Larsen - true - true true https://github.com/angularsen/UnitsNet https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png @@ -23,11 +21,17 @@ netstandard2.0;net40 UnitsNet CS1701;CS1702;CS1705;CS0618;CS0809;CS1591 + + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + diff --git a/appveyor.yml b/appveyor.yml index 7288bf1497..199338deae 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -5,8 +5,8 @@ skip_commits: - docs/* - '**/*.md' -# fetch repository as zip archive, not doing any git operations on it -shallow_clone: true +# Only fetch the latest commits to reduce time to download on agent, but support pushes containing multiple commits +clone_depth: 50 # build cache to preserve files/folders between builds cache: